简体   繁体   中英

Angularjs directive create click event

I have simple directive, like this:

    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>

and I would like create event for click to button, and after it in my controller use this event. But I don't know how to do it. Help me pls. Thanks a lot.

I would suggest using something Angular already gives you: ng-click .

Here's a JSBin example that I did for you:

<div ng-controller="Controller">
  <div my-customer ng-click='clicke()'></div>
</div>

If you click on the directive, it should look like this:

在此处输入图片说明

You can use ng-repeat to iterate over an array of customers and then have your ng-click function take parameters assocaited to which customer (index in the array) is being displayed...

<div ng-repeat="customer customers track by $index" ng-click="myClickHandler(index)">
  {{customer}}
</div>

I would suggest following solution. A working example can be found at - @sumit Plunker
Here's a code sample:

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);
        })
      }
    }
  });

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