简体   繁体   中英

Angular.js: custom directive

I am trying to add custom directive in my app. But it is not getting called on button click event.

my controller-

appServices.directive('customClick', function() {
  return {
    restrict: 'E',
    require: 'ngModel',
    link: function($scope, element, attrs) {
            $scope.deleteFieldMap = function() {
              alert('inside click');
            }
          }
  }
}

my 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>

What i am doing wrong here?

Your directive is restricted to 'E'. Which means to "element".

You should change it to 'A' since you expect an it as an "attribute".

Check out the reference documentation :

https://docs.angularjs.org/guide/directive

Edit : As explained by Medet, you also miss the "ng-model" on your element. Remove the definition if is his unecessary or add the attribute if you really expect it. Regards

First issue as noted above is element.restrict: 'A' , seconds issue - you must have ng-model attribute on your button, demo below

 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> 

you should use your custom directive as follow:

<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>

as an element!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM