[英]Angular.js: custom directive
我試圖在我的應用程序中添加自定義指令。 但這並沒有在按鈕單擊事件上被調用。
我的控制器
appServices.directive('customClick', function() {
return {
restrict: 'E',
require: 'ngModel',
link: function($scope, element, attrs) {
$scope.deleteFieldMap = function() {
alert('inside click');
}
}
}
}
我的jsp
<button custom-click class="btn btn-danger btn-sm"
data-style="zoom-in"
ng-click="deleteFieldMap(editProductJob,$index)"
name="jobFileKey"
title="Delete" >
<span class="glyphicon glyphicon-remove"></span>
</button>
我在這里做錯了什么?
您的指令僅限於“ E”。 意思是“元素”。
您應該將其更改為“ A”,因為您希望將其作為“屬性”。
查看參考文檔:
https://docs.angularjs.org/guide/directive
編輯:正如Medet解釋的那樣,您還錯過了元素上的“ ng-model”。 如果不需要定義,請刪除該定義;如果確實需要,請添加該屬性。 問候
如上所述,第一個問題是element.restrict: 'A'
,第二個問題-您的按鈕上必須具有ng-model
屬性,下面是演示
angular.module('app', []) .run(function($rootScope) { $rootScope.test = '123qe'; }).directive('customClick', function() { return { restrict: 'A', require: 'ngModel', link: function($scope, element, attrs, ngModelCtrl) { $scope.deleteFieldMap = function() { alert('inside click' + ngModelCtrl.$viewValue); } } } });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.js"></script> <div ng-app="app"> <button custom-click ng-click="deleteFieldMap(editProductJob,$index)" ng-model="test"> remove </button> </div>
您應該按照以下方式使用自定義指令:
<custom-click class="btn btn-danger btn-sm"
data-style="zoom-in"
ng-click="deleteFieldMap(editProductJob,$index)"
name="jobFileKey"
title="Delete" >
<span class="glyphicon glyphicon-remove"></span>
</custom-click>
作為元素!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.