使用AngularJs在ng-bind-html中观察ng-model

时间:2018-02-21 17:23:00

标签: angularjs angularjs-filter watch angularjs-ng-model ng-bind-html

这是我的标记

<div ng-app="myApp" ng-controller="myCtrl">
    <input type="text" ng-model="name">
    <p ng-bind-html="myText|unsafe"></p>
</div>

我正在使用此代码

var app = angular.module("myApp", ['ngSanitize']);
app.controller("myCtrl", function($scope) {
    $scope.myText = "My name is: <h1>{{name}}</h1>";
    $scope.name="Habib";
});
app.filter('unsafe', function ($sce) {
    return function(val) {
        return $sce.trustAsHtml(val);
    };
});

输出:

  

我的名字是:{{}}

期望输出:

  

我的名字是:Habib

我希望它也应该反映文本框中的值。

1 个答案:

答案 0 :(得分:1)

修改

您遇到$scope.name绑定问题的原因是ng-bind-html未将该html绑定到当前范围。您可以使用指令来解决此问题。 Here是解决问题的答案。

Here是一个添加指令并显示您正在寻找的行为的plunker。

以下是添加的指令可解决您的问题:

app.directive('compileTemplate', function($compile, $parse){
   return {
       link: function(scope, element, attr){
           var parsed = $parse(attr.ngBindHtml);
           function getStringValue() {
                return (parsed(scope) || '').toString();
           }

            // Recompile if the template changes
            scope.$watch(getStringValue, function() {
                // The -9999 makes it skip directives
                // so that we do not recompile ourselves
                $compile(element, null, -9999)(scope);  
            });
        }
    }
});

您需要在$scope.name="Habib"范围变量之前声明myText

var app = angular.module("myApp", ['ngSanitize']);
app.controller("myCtrl", function($scope) {
    $scope.name="Habib";
    $scope.myText = "My name is: <h1>{{name}}</h1>";
});
app.filter('unsafe', function ($sce) {
    return function(val) {
        return $sce.trustAsHtml(val);
   };
});