我需要一些关于使用 ng-bind-html 创建的 ng-model 的帮助。我在服务器中有一个 JSON 文件,其中有一些 html 和一些输入,如下所示:
*.json
{
"test": {
"1": {
"question":"<span>1. something:</span>",
"options":"<input type='radio' name='q1' ng-model='q.1' value='a'>a) op 1<br><input type='radio' name='q1' ng-model='q.1' value='b'>b) op 2<br><input type='radio' name='q1' ng-model='q.1' value='c'>c) op 3<br><input type='radio' name='q1' ng-model='q.1' value='d'>d) op 4<br><input type='radio' name='q1' ng-model='q.1' value='e'>e) op 5<br>",
"answer":"c"
},
"2": {
...
}
}
}
然后在我的 HTML 文件中我有类似的内容:
<div class="testContent">
<div class="test">
<div class="questions" ng-repeat="qs in questions" ng-show="questions.length">
<div ng-bind-html="qs.question"></div>
<div class="options" ng-bind-html="qs.options">
</div>
</div>
</div>
<br>
<div class="nextBtn">
<a href="#test/6" class="btn btnNext" ng-click="save()"> continue ></a>
</div>
</div>
在我的 Angular Controller 中,我对 JSON 文件进行了 ajax 调用:
Controller :
.controller('testCtrl', ['$scope', '$http', 'myService', '$sce',
function($scope, $http, myService, $sce, ){
$http.get(urls.url_otis).success(function(data, status){
angular.forEach(data.test, function(value, key){
var q = data.test[key];
q[key] = key;
q.question = $sce.trustAsHtml(q.question);
q.options = $sce.trustAsHtml(q.options);
$scope.questions.push(q);
});
}).error(function(data, status){console.log(status)});
}
html 已填充,但我无法将 $watch 用于通过此方法生成的模型 (q)。
我如何$监视以这种方式创建的模型的变化?
提前致谢...
最佳答案
您必须编译动态创建的元素才能让 Angular 了解它们。
可以执行此操作的指令可能如下所示:
app.directive('compile',function($compile, $timeout){
return{
restrict:'A',
link: function(scope,elem,attrs){
$timeout(function(){
$compile(elem.contents())(scope);
});
}
};
});
$timeout
用于在 ng-bind-html
完成其工作后运行编译函数。
现在你可以简单地将 compile
作为 div 的属性,并使用 ng-bind-html
:
<div class="questions" ng-repeat="item in questions" ng-show="questions.length" >
<div ng-bind-html="item.question"></div>
<div compile class="options" ng-bind-html="item.options"></div>
</div>
fiddle :http://jsfiddle.net/nZ89y/7/
关于angularjs - 如何监视使用 ng-bind-html 创建的 ng-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24560540/