[英]Trigger to click on an html element in angular.js
我目前有一個指令。 當我使用“單擊以編輯”指令單擊元素時,將顯示一個文本字段以編輯內容。
我想要當我單擊按鈕時,這種現象繼續發生。 我需要單擊按鈕時,它等效於單擊指令。 我該如何實現?
<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>
要實現您必須執行的操作,可以使用角度事件 , 也可以通過隔離范圍共享對象並向其中添加功能 。
例子:
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;
}
}
}
});
修改指令,在其中添加按鈕控件的click bind事件。 因此,在調用偽指令時,它將綁定按鈕上的click事件。 希望這可以幫助 !
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.