我正在尝试使用过滤器动态生成一个 ng-model 指令。 主要思想是数据库中有一些文本。此文本在方括号([1]、[2] 等)之间存在由数字定义的间隙。目的是解析这些差距并将它们转化为输入。然后应该使用 ng-model 指令将这些输入绑定(bind)到一个变量,但我无法让它工作。
这是我的 Controller :
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”变量绑定(bind)模型。 这是我的指令:
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”变量绑定(bind)。 对于我一直在阅读的内容,这是因为我必须再次重新编译模板,以便 Angular 再次解析所有 ng-directives。尝试执行以下操作但没有任何运气:
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));
});
}
}
}]);
但它仍然没有绑定(bind)模型。即使是最简单的事情,Angular 也有多么困难,我开始感到有点沮丧,因此非常感谢任何帮助。
谢谢
最佳答案
我还没有测试过这段代码,但这里的要点是你可以在你的 ng-repeat 上使用内联过滤器来分割“间隙”。这将返回一个项目数组,您可以以此为基础构建您的模型。
<div ng-repeat="exercise in firstExercise">
<div ng-repeat="(questionId, question) in exercise.q | gapToInput">
<input ng-repeat="" type="text" ng-model="exercise.q[questionId].answer">
</div>
</div>
你的过滤器在哪里:
app.filter('gapToInput', function(){
return function(input){
return input.split(/\[[0-9]\]/g);
};
});
关于javascript - 在 AngularJS 中动态生成 ng-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27531209/