How to fix unexpected arguments passing from a function being on ng-change for select list?

我怕爱的太早我们不能终老 提交于 2019-12-23 18:01:18

问题


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

Directive 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'
      }];

Template code

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

Code for directive usage

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

So, the arguments being passed to someFunction() is being undefined or it contains correct value, the behaviour is unexpected and random.


回答1:


Your template should call a method by passing a parameter in JSON format like ng-change="ngChange({someModel: ngModel})" from directive

Make sure while calling function from directive you should pass parameter with the key should be function parameter name as here it is someModel and then pass the value like here 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



来源:https://stackoverflow.com/questions/32148868/how-to-fix-unexpected-arguments-passing-from-a-function-being-on-ng-change-for-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!