How to fix unexpected arguments passed from a function located on ng-change for a selected list?

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

Directory Code

.directive('inputSelect', function() { return { templateUrl: 'someTemplate.html', restrict: 'E', scope: { ngModel: '=', ngChange: '&', options: '=' } }; }) 

Controller code

  $scope.someFunction = function(name) { console.log(name) }; $scope.colors = [{ name: 'black', shade: 'dark' }, { name: 'white', shade: 'light', notAnOption: true }, { name: 'red', shade: 'dark' }]; 

Pattern code

 <select ng-model="ngModel" ng-change="ngChange()" ng-options="option.name for option in options"> </select> 

Code for using the directive

 <input-select ng-model="someModel" ng-change="someFunction(someModel.name)" options="colors"></input-select> 

So, the arguments passed to someFunction() are undefined or contain the correct value, the behavior is unexpected and random.

+3
source share
1 answer

Your template should call the method, passing the parameter in JSON format, for example ng-change="ngChange({someModel: ngModel})" from the directive

Make sure that when calling the function from the directive, you must pass the parameter with the key, this should be the name of the function parameter, since here is someModel , and then pass the value, as here, to its ngModel

Markup

 <input-select ng-model="someModel" ng-change="someFunction(someModel)" options="colors"></input-select> 

Directive Template

 <select ng-model="ngModel" ng-change="ngChange({someModel: ngModel})" ng-options="option.name for option in options"> </select> 

Working plunkr

+2
source

All Articles