ng-change方法没有执行

时间:2014-01-21 19:04:39

标签: angularjs ng-options angularjs-ng-change

我正在尝试传递a中选择的对象来更新另一个对象的数据。 这是html

  <select id="categoryListBox"
                ng-model="category.selected"
                ng-change="updateCategory(category.selected)"
                ng-options="category._id as category.name for category in categories">
        </select>

这呈现

<select id="categoryListBox" 
    ng-model="category.selected" 
    ng-change="updateCategory()" 
    ng-options="category._id as category.name for category in categories" 
    class="ng-valid ng-dirty">
    <option value="0" selected="selected">Test4</option>
    <option value="1">Test5</option>
 </select>

这是我的更新功能

$scope.updateCategory = function(){
    console.log('hi');
}

我的问题是,现在当所选项目发生更改时,updateCategory方法不会触发。我想在<select></select>中选择的选项更改我的$ scope.updateCategory方法时触发。如果我可以将选择的类别传递给此方法,那也很棒。

这里更新的是我的初始化,它填充了数组类别

$scope.init = function (){
            console.log('dfakjsdhf');
            console.log(apiUrl);
            $scope.category = {};
            $scope.subcategory = {};
            //$scope.categories = {_id: 1, name:'test'};

            $http({ method: 'GET', url: apiUrl + '/categories'}).
                success(function (data, status, headers, config) {
                    $scope.categories = data;
                    console.log($scope.categories);

                }).
                error(function (data, status, headers, config) {
                    console.log('error');
                });


        };

2 个答案:

答案 0 :(得分:0)

无需在函数中传递category.selected。在你的js控制器中它将在你的范围内,只需在你的updateCategory()函数中使用它。

JSFiddle

HTML:

<select id="categoryListBox"
            ng-model="category.selected"
             ng-change="updateCategory()"
            ng-options="category.id as category.name for category in categories">
    </select>

JS:

$scope.updateCategory = function(){
    alert($scope.category.selected);
}

答案 1 :(得分:0)

只需将您的ng模型从category.selected重命名为其他内容。根据我的理解,在你的代码中,ng-options category 和ng-model category

之间存在歧义。
<select id="categoryListBox"
            ng-model="categorymodel"
            ng-change="updateCategory(categorymodel)"
            ng-options="category.id as category.name for category in categories">
    </select>

DEMO