【问题标题】:Watch ng-model in ng-bind-html using AngularJs使用 AngularJs 在 ng-bind-html 中观看 ng-model
【发布时间】:2018-02-21 17:22:59
【问题描述】:

这是我的标记

<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);
    };
});

输出:

我的名字是:{{}}

所需的输出:

我的名字是:哈比卜

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

【问题讨论】:

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


    【解决方案1】:

    编辑

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

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

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

    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);  
                });
            }
        }
    });
    

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

    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);
       };
    });
    

    【讨论】:

    • 好的,但是输入的值将如何反映
    • 当您在输入中编辑文本时它应该会更新。您可能需要在控制器中使用 $scope.$apply() 来触发摘要循环以更新变量。
    • @habib 我编辑了最初的答案并找到了您遇到问题的原因。
    • 太好了!谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    • 2015-04-02
    • 2015-09-04
    • 1970-01-01
    相关资源
    最近更新 更多