【发布时间】:2014-12-18 23:55:49
【问题描述】:
我正在尝试使用过滤器动态生成 ng-model 指令。 主要思想是数据库中有一些文本。此文本有由方括号([1]、[2] 等)之间的数字定义的空白。目的是解析这些差距并将它们转化为输入。然后应该使用 ng-model 指令将这些输入绑定到一个变量,但我无法让它工作。
这是我的控制器:
app.controller('exerciseTemplateCtrl', ['$http', '$scope', '$sce', '$filter', '$compile', function($http, $scope, $sce, $filter, $compile){
// used to test the binding through ng-model
$scope.answers = [];
$http.get('encode_exercises.json')
.then(function(response){
$scope.firstExercise = response.data;
});
$scope.parseHtml = function(input){
input = $filter('gapToInput')(input);
return $sce.trustAsHtml(input);
};
}]);
这是我的过滤器“gapToInput”
app.filter('gapToInput', function(){
return function(input){
return input.replace(/\[[0-9]\]/g, '<input type="text" ng-model="answers">');
};
});
如您所见,我正在使用“answers”变量绑定模型。 这是我的指令:
app.directive('exerciseTemplate', function(){
return{
restrict: 'E',
templateUrl: 'exercise-template.html'
};
});
index.html 包含前面的指令:
<exercise-template></exercise-template>
这里是我的上一个指令的模板(简化)
<div ng-controller="exerciseTemplateCtrl as e">
<div ng-repeat="exercise in firstExercise">
<div ng-repeat="(questionId, question) in exercise.q">
<div ng-bind-html="parseHtml(question.d.q)"></div>
</div>
</div>
<p><button>Check</button></p>
</div>
question.d.q 包含来自数据库的带有空白的文本([1]、[2] 等),它正在成功应用过滤器(抱歉,我没有足够的声誉来发布图片):
http://i.stack.imgur.com/W0NoI.png
问题在于,即使替换有效,ng-model 指令也不会将每个输入与“answers”变量绑定。 对于我一直在阅读的内容,这是因为我必须再次重新编译模板,以便 Angular 再次解析所有 ng 指令。尝试做以下没有任何运气:
var scope = $scope;
$scope.parseHtml = function(input){
input = $filter('gapToInput')(input);
input = $compile(input)(scope);
return $sce.trustAsHtml(input);
};
我也关注了this thread,并尝试将指令格式更改为以下内容:
app.directive('exerciseTemplate', ['$compile', '$http', function($compile, $http){
return {
restrict: 'E',
link: function(scope, element, attrs){
$http.get('exercise-template.html').then(function(result){
element.replaceWith($compile(result.data)(scope));
});
}
}
}]);
但它仍然没有绑定模型。即使是最简单的事情,我也开始对 Angular 的困难程度感到有点沮丧,所以任何帮助都将不胜感激。
谢谢
【问题讨论】:
标签: javascript html angularjs