我创造了一个plunker http://plnkr.co/edit/1kvYuxD3PpUXvB0G5W33?p=preview
我想创建一个可以采用范围字段的指令,并使用添加按钮我想在范围字段中推送一些值。这是两个问题
我无法在按钮上附加事件但能够在主要指令元素上附加事件。我知道我可以使用jquery的委托但这不是正确的方法。
(已解决)当附加事件时我正在更新范围,但问题是它没有更新布局,直到在$ scope中更改了某些内容或提交了表单。 (Shivkumar的评论解决了这个问题)
我想让这个指令可重用,即
我想对不同的字段多次使用此指令。 我的指令名是arrayfield
<div arrayfield model="employee.docs" title="Documents"></div>
<div arrayfield model="employee.docsPrimary" title="Primary Documents"></div>
指令代码。
app.directive('arrayfield', function() {
return {
restrict: 'EA',
scope: {
data: '=model',
title: '@'
},
link:function link(scope, element, attrs) {
//always gettign this emply
console.log(element.find("#addBtn"));
scope.$watch('data',function(){
console.log("SOmething updated");
});
element.bind("click",function(){
//If data exist push are assign new one
(scope.data && scope.data.push({})) || (scope.data=[{}]);
scope.$apply(); // thanks Shivkumar for answring in comment
});
},
templateUrl: 'arrayField.html'
};
});
如果您需要更多信息,请与我们联系。
复制问题我可以点击添加文档,然后在其他字段中输入任何内容,应该添加新元素,但我想在我点击添加文档按钮后立即添加
答案 0 :(得分:2)
您可以在指令范围
上定义该功能link: function link(scope, element, attrs) {
scope.click = function() {
//If data exist push are assign new one
(scope.data && scope.data.push({})) || (scope.data = [{}]);
};
然后使用模板中的ng-click
将其附加到按钮:
<button ng-click="click()" type="button" class="addBtn" id="addBtn">Add {{title}}</button>
注意,不需要scope.$apply
。以下是您的plunker的更新:http://plnkr.co/edit/yeWQwz7yHnTZmaipu3Vx?p=preview