从下拉列表中选择选项时触发角度函数

时间:2016-07-11 16:04:28

标签: javascript angularjs angularjs-select

我通过拨打api来填充选择下拉菜单。当用户从选择菜单中选择一个选项时,我希望触发第二个功能 - $scope.getRoles()。然而,这是立即开火。任何想法为什么会这样?请参阅下面我尝试的代码。

HTML

<select>
     <option ng-change="getRoles()" ng-repeat="country in countries">{{ country.countryCode }}</option>   
</select>

app.controller("jobsCtrl", function($scope, careerData) {

    //get list of countries when app loads
    careerData.countryList().then(function successCallback(response) {
            $scope.countries = response.data;   
            $scope.countries.unshift({countryCode: "Select a country"}); 
        }, function errorCallback(response) {  
            console.log(response);
    });

    $scope.getRoles = careerData.jobByCountry().then(function successCallback(response) {
            console.log(response)
        }, function errorCallback(response) {  
            console.log(response);
    })
});

app.factory('careerData', ['$http', function($http){
return {

     countryList: function() {
        return $http({
            method: 'GET',
            url: 'testUrl'
        })
    },

    jobByCountry: function() {
        return $http({
            method: 'GET',
            url: 'someurl'
        })
    }
}
}]);

2 个答案:

答案 0 :(得分:0)

首先,您应该使用ngOptions

更改

<select>
  <option ng-change="getRoles()" ng-repeat="country in countries">{{ country.countryCode }}</option>   
</select>

作为

<select ng-options="country as country.countryCode for country in countries" ng-model="countrySelected" ng-change="getRoles()">  
</select>

示例:

angular.module('app', [])
  .controller('mainCtrl', function($scope) {
    $scope.cars = ["Audi", "BMW", "Corolla", "Mercedes"];

    $scope.check = function() {
      console.log($scope.car);
    }
  });
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="mainCtrl">
    Cars:
    <select ng-model="car" ng-options="car for car in cars" ng-change="check()">
       <option value="">Select a car</option>
    </select>
</body>

</html>

答案 1 :(得分:0)

所以我认为您正在寻找

(ngModelChange)="getRoles()"

在您的HTML标记中。

这将在您更改它适用于我在这里遇到的大多数输入字段的模块时触发,因为它不适用于mat-select。

这是针对角度7的。这也是一个古老的问题。

评论:

但是我希望这会对您有所帮助,因为如果先前的答案有效,仍然无法解决问题。