【发布时间】:2015-07-10 05:41:33
【问题描述】:
我的指令中有一个带有文本框的模板,单击按钮(添加)时,我重复相同的指令 10 次,因此文本框将出现 10 次,但每个文本框的 ng-model 将保持相同,我需要动态化,以便在模板 ng-model 的每次重复时变得不同。 问题是我无法为文本框创建动态 ng-model 以区分输入的值,以便我可以在控制器中访问它。如何使文本框模型动态化。
App.directive("configDirectives", function($compile) {
return {
restrict: 'EA',
link: function(scope, element, $attr) {
console.log('Scope in directive : ' + scope);
scope.add = function() {
console.log("Inside directive value of satCount", satCount++);
$newDirective = angular.element('<add-config></add-config>');
element.append($newDirective);
$compile($newDirective)(scope);
console.log('Scope in directive : ' + scope);
}
}
}).directive("addConfig", function() {
return {
restrict: 'AE',
template: '<div>{{scope.satCount}}' +
'<input type="text" ng-model="x"/>' +
'</div>',
link: function(scope, element, attribute) {
scope.remove = function() {
element.remove();
}
}
});
<!-- Controller -->
(function() {
var self = null;
var ConfigRuleClass = Class.extend({
init: function($scope, configService) {
self = this;
self.$scope = $scope;
},
save: function() {
console.log("values from parent configuration---");
console.log("config1---", self.lstConfigs.name);
console.log("Dynamic Filed Data" + self.dynamicConfigs);
}
});
App.controller("ConfigRuleCntrl", ['$scope', 'configService', ConfigRuleClass]);
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="xx" data-ng-controller="ConfigRuleCntrl as y">
<input type="text" ng-model="y.x" />
<button data-ng-click="add()">Add</button>
<br>
<button data-ng-click="y.save()">SAVE</button>
<config-directives></config-directives>
</div>
【问题讨论】:
-
您可以为您的问题创建 plnkr 吗?
-
如何重复文本框?
-
应该是我们在这里缺少的 ng-repeat 吗?
-
点击按钮(添加)我正在添加文本框,即每次点击只需要重复一次我的模板。使用指令重复它,我编写了一个在点击时调用的添加方法添加的
-
你能把指令的代码和
add()函数的代码贴出来吗,因为它们似乎是这里的主要代码......
标签: angularjs