AngularJS ng-bind-html 2way 数据绑定 [英] AngularJS ng-bind-html 2way data binding
本文介绍了AngularJS ng-bind-html 2way 数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 AngularJS 应用程序,我从网络服务中获取了一些数据,并使用 ng-bind-html 将一些 HTML 解析为模板......但是当我尝试在 ng-bind-html 中绑定数据时 - 什么也没有发生.. 任何人?
我这里有一个小例子,.. 不是正确的情况.
HTML
<div ng-bind-html="post"></div>
Javascript
angular.module('myApp',[]).controller('MyCtrl', function($scope, $sce) {$scope.name = '世界';$scope.post = $sce.trustAsHtml("<h1>hello {{name}}</h1>");});
解决方案
添加此指令
angular.module("myApp").directive('compileTemplate', ["$compile", "$parse", function($compile, $parse) {返回 {限制:'A',链接:函数($scope,元素,属性){var parse = $parse(attr.ngBindHtml);function value() { return (parse($scope) || '').toString();}$scope.$watch(value, function() {$compile(element, null, -9999)($scope);});}}}]);
I have an AngularJS app where I got some data from a webservice and parse some HTML to the template with ng-bind-html ... but when I try to bind data inside the ng-bind-html - nothing happens .. anyone?
I have a little example here,.. not the right case.
HTML
<div ng-controller="MyCtrl">
<div ng-bind-html="post"></div>
</div>
Javascript
angular.module('myApp',[])
.controller('MyCtrl', function($scope, $sce) {
$scope.name = 'World';
$scope.post = $sce.trustAsHtml("<h1>hello {{name}}</h1>");
});
解决方案
Add this directive
angular.module("myApp").directive('compileTemplate', ["$compile", "$parse", function($compile, $parse) {
return {
restrict: 'A',
link: function($scope, element, attr) {
var parse = $parse(attr.ngBindHtml);
function value() { return (parse($scope) || '').toString(); }
$scope.$watch(value, function() {
$compile(element, null, -9999)($scope);
});
}
}
}]);
这篇关于AngularJS ng-bind-html 2way 数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文