Taras Kovalenko
Taras Kovalenko

Reputation: 2393

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.

Upvotes: 0

Views: 917

Answers (3)

Sumit Deshpande
Sumit Deshpande

Reputation: 2155

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

Upvotes: 1

Maxwelll
Maxwelll

Reputation: 2212

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>

Upvotes: 1

Josh Beam
Josh Beam

Reputation: 19772

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:

enter image description here

Upvotes: 1

Related Questions