[英]Angularjs directive create click event
我有一個簡單的指令,像這樣:
angular.module('docsTemplateUrlDirective', [])
.controller('Controller', ['$scope', function($scope) {
$scope.customer = {
name: 'Naomi',
address: '1600 Amphitheatre'
};
$scope.clicke = function(){
alert('test');
};
}])
.directive('myCustomer', function() {
return {
templateUrl: 'my-customer.html'
};
});
index.html
<div ng-controller="Controller">
<div my-customer click-event='clicke()'></div>
</div>
my-customer.html
Name: {{customer.name}} Address: {{customer.address}}
<button>click</button>
我想為單擊按鈕創建事件,然后在控制器中使用此事件。 但是我不知道該怎么做。 請幫助我。 非常感謝。
您可以使用ng-repeat
遍歷一系列客戶,然后讓ng-click
函數采用與正在顯示的客戶(數組中的索引)相關的參數...
<div ng-repeat="customer customers track by $index" ng-click="myClickHandler(index)">
{{customer}}
</div>
我建議以下解決方案。 一個有效的例子可以在- @sumit Plunker找到
這是一個代碼示例:
angular.module('docsTemplateUrlDirective', [])
.controller('Controller', ['$scope', function($scope) {
$scope.customer = {
name: 'Naomi',
address: '1600 Amphitheatre'
};
$scope.clicke = function(evt) {
alert('test');
};
}])
.directive('myCustomer', function($parse) {
return {
restrict: 'A',
scope: true,
templateUrl: 'my-customer.html'
}
})
.directive('clickEvent', function($parse) {
return {
restrict: 'A',
scope: true,
link: function(scope, el, attrs) {
var expressionHandler = $parse(attrs.clickEvent)
el.find('#btnSubmit').on('click', function(e) {
expressionHandler(scope);
})
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.