StuperUser
StuperUser

Reputation: 10850

How can I set the ng-change attribute on some mark up inside my custom directive?

I have a custom directive that contains a <select> and an <input>.

If I put <my-custom-directive ng-change="vm.someFunction()">, how can I add the ng-change to the <select> inside the markup in the template of the directive?

Upvotes: 0

Views: 1029

Answers (2)

Gergo Gera
Gergo Gera

Reputation: 46

You can pass functions to your directive's scope by using '&'. So when you define your directive, specify the scope the following way:

scope: {
'myChangeFunction' : '&'
}

In your template you can use it

<select ng-change="myChangeFunction()">

In your client code you can specify this:

<my-custom-directive my-change-function="vm.someFunction()">

Upvotes: 3

Diego Unanue
Diego Unanue

Reputation: 6836

If I don't misunderstand your question, you want to add the directive ng-change to a select inside the directive template. Just add the ng-change to the select and handle the event in the directive's controller.

The directive template:

<select ng-model="model.id" ng-change="selectChange()">
  <option value="0">Zero</option>
  <option value="1">One</option>
 <option value="2">Two</option>

The directive:

  app.directive("testDirective", function(){
   return{
    restrict: 'E',
    templateUrl: 'testDirective.html',
    controller: function($scope){
        $scope.selectChange = function(){
          console.log('select change!');
        }
     }
   }
  })

Take a look at this plunker.

http://plnkr.co/edit/U184Z8rSjxa6NFEw0n4t?p=preview

Upvotes: 0

Related Questions