0

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
StuperUser
  • 10,555
  • 13
  • 78
  • 137

2 Answers2

3

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()">
Gergo Gera
  • 46
  • 1
0

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

Diego Unanue
  • 6,576
  • 8
  • 47
  • 67