如何使Angularjs $ setViewValue处理HTML

时间:2015-04-22 21:46:51

标签: angularjs

与angularjs在页面底部的示例@ https://code.angularjs.org/1.3.7/docs/api/ng/type/ngModel.NgModelController

一样

将一些空格重复地重新分配到     

app.directive('contenteditable', ['$sce','$interpolate', function($sce, $interpolate) {
  return {
    restrict: 'A', // only activate on element attribute
    require: '?ngModel', // get a hold of NgModelController
    link: function(scope, element, attrs, ngModel) {
      if (!ngModel) {return;} // do nothing if no ng-model

      // Specify how UI should be updated
      ngModel.$render = function() {
        console.log("$rendering : "+ngModel.$viewValue);
        element.html(ngModel.$viewValue);
        console.log("new html: "+element.html());
        window.setTimeout(function() {console.log("delayed new html: "+element.html());}, 500);
      };

      // Listen for change events to enable binding
      element.on('blur keyup change', function() {
        scope.$evalAsync(read);
      });
      //read(); // initialize
      ngModel.$setViewValue($interpolate(element.html())(scope));
      ngModel.$render();

      // Write data to the model
      function read() {
        var html = element.html();
        // When we clear the content editable the browser leaves a <br> behind
        // If strip-br attribute is provided then we strip this out
        if ( attrs.stripBr && html == '<br>' ) {
          html = '';
        }
        console.log('setViewValue = '+html);
        ngModel.$setViewValue(html);
        ngModel.$render();
      }
    }
  };
}]);

返回

*.js:75 setViewValue = &nbsp;
*.js:53 $rendering : &nbsp;
*.js:55 new html: &nbsp;
*.js:56 delayed new html: &nbsp;&amp;nbsp;
*.js:75 setViewValue = &nbsp;&amp;nbsp;
*.js:53 $rendering : &nbsp;&amp;nbsp;
*.js:55 new html: &nbsp;&amp;nbsp;
*.js:56 delayed new html: &amp;nbsp;&amp;amp;nbsp;
*.js:75 setViewValue = &nbsp;&amp;nbsp;&amp;amp;nbsp;
*.js:53 $rendering : &nbsp;&amp;nbsp;&amp;amp;nbsp;
*.js:55 new html: &nbsp;&amp;nbsp;&amp;amp;nbsp;
*.js:56 delayed new html: &amp;nbsp;&amp;amp;nbsp;&amp;amp;amp;nbsp;

如果我ngModel.$setViewValue(html+'<span></span>');我得到了正确的HTML,但它会像&nbsp; &nbsp; <span></span><span></span><span></span><span></span>一样被破坏,但仍会破坏模型的价值。

那么我可以让$ setViewValue接受HTML,还是可以在不破坏HTML的情况下删除<span></span>

1 个答案:

答案 0 :(得分:1)

显然这一切都取决于模型如何初始化

当我做的时候

echo "<input type=hidden id=porc name=porc value='$prepdel'>";

<script type="text/javascript">
    if(document.getElementById("porc").value > 0)
    {
        showpnd();
        showcpu();
    }
</script>
</body>

或只是

ngModel.$setViewValue($interpolate(element.html())(scope));
ngModel.$render();

失败了。但是,如果我只是做

ngModel.$setViewValue($interpolate(element.html())(scope));

然后它完美无缺,甚至不需要那些愚蠢的ngModel.$render();

所以生成的代码看起来像

<span></span>