我从 Controller 注入(inject) html 输入,我正在尝试绑定(bind)范围变量,但它不起作用。
这是我的代码
HTML :
<div ng-controller='addHTML'>
<div ng-bind-html="trustedHtml"></div>
<code>{{user}}</code>
</div>
CSS :
var app = angular.module('app',[]);
var addHTML = function ($scope,$sce) {
$scope.user = {};
$scope.user.someVariable = "";
//inject some html
$scope.html = '<input type="text" ng-model="user.someVariable">';
$scope.trustedHtml = $sce.trustAsHtml($scope.html);
};
你可以在这里找到它:http://jsbin.com/miluguni/1/watch?html,js,output
输入输入时,范围变量不会更改。
最佳答案
ngBindHtml
指令不会 $compile 模板,它只会将模板插入 DOM。
我复制了ngBindHtml
( source code ) 并添加了 $compile
新指令:
app.directive('compileHtml',['$sce', '$parse', '$compile',
function($sce, $parse, $compile){
return {
link: function(scope,element,attr){
var parsed = $parse(attr.compileHtml);
function getStringValue() { return (parsed(scope) || '').toString(); }
scope.$watch(getStringValue, function (value) {
var el = $compile($sce.getTrustedHtml(parsed(scope)) || '')(scope);
element.empty();
element.append(el);
});
}
};
}]);
模板:
<div compile-html="trustedHtml"></div>
这是一个演示:http://jsbin.com/miluguni/3/edit
关于angularjs - 如何将 Controller 绑定(bind)到动态添加的 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21914760/