我目前有一个指令。当我点击带有“点击编辑”指令的元素时,会显示一个文本字段来编辑内容。
我希望当我点击按钮时,此行为将继续发生。 我需要在单击按钮时,它相当于单击指令。我怎样才能做到这一点?
<label>Sprint name:</label> <div click-to-edit type="inputText" ng-model="sprintName"></div>
<br/>
<input type='button' value='trigger Directive' ng-click='triggerDirective()'>
</div>
答案 0 :(得分:1)
要实现您的目标,您可以使用angular events或you can share an object through isolate scope and add a function to it。
示例:
1-使用Angularjs事件:(PLUNKER)
HTML:
<div click-to-edit></div>
<button type="button" ng-click="item.toggle()">Toggle from Controller</button>
控制器:
app.controller('MainCtrl', function($scope) {
$scope.toggle = function(){
//Emit the event
$scope.$broadcast('app.myEvent');
};
});
指令:
app.directive('clickToEdit', function() {
return {
restrict: 'A',
template: `
<div ng-show="editState">
<div>
<input type="text"/>
<button type="button" ng-click="item.toggle()">Cancel</button>
</div>
</div>
`,
link: function (scope, element, attrs) {
scope.editState = false;
scope.toggle = function () {
scope.editState = !scope.editState;
}
//Listen and handler the event
scope.$on('app.myEvent', function(event){
scope.toggle();
});
}
}
});
2-通过隔离范围共享对象:(PLUNKER)
HTML:
<div click-to-edit item="item"></div>
<button type="button" ng-click="item.toggle()">Toggle from Controller</button>
控制器:
app.controller('MainCtrl', function($scope) {
$scope.item = {};
});
指令:
app.directive('clickToEdit', function() {
return {
restrict: 'A',
scope: {
item: '='
}
template: `
<div ng-show="editState">
<div>
<input type="text"/>
<button type="button" ng-click="item.toggle()">Cancel</button>
</div>
</div>
`,
link: function (scope, element, attrs) {
scope.editState = false;
//Here you add the function to the isolate scope 'item' variable
scope.item.toggle = function () {
scope.editState = !scope.editState;
}
}
}
});
答案 1 :(得分:0)
修改指令,在其中添加按钮控件的click bind事件。因此,当调用该指令时,它会绑定按钮上的click事件。 希望这有帮助!