car*_*amo 8 watch angularjs ng-bind-html
我需要一些使用ng-bind-html创建的ng模型的帮助.我在服务器中有一个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": {
...
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后在我的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>
Run Code Online (Sandbox Code Playgroud)
在我的Angular控制器中,我有对JSON文件的ajax调用:
控制器:
.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)});
}
Run Code Online (Sandbox Code Playgroud)
html已填充,但我不能使用$ watch来使用此方法生成的模型(q).
我怎样才能观察以这种方式创建的模型的变化?
提前致谢...
akn*_*akn 16
您必须编译动态创建的元素以让角度了解它们.
可以做到这一点的指令可能看起来像这样:
app.directive('compile',function($compile, $timeout){
return{
restrict:'A',
link: function(scope,elem,attrs){
$timeout(function(){
$compile(elem.contents())(scope);
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
$timeout用来运行编译功能,ng-bind-html完成它的工作.
现在你只需将compilediv的属性作为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>
Run Code Online (Sandbox Code Playgroud)
小提琴:http://jsfiddle.net/nZ89y/7/
| 归档时间: |
|
| 查看次数: |
8069 次 |
| 最近记录: |