AngularJS-ng更改未启动

AngularJS - ng-change not firing

本文关键字:启动 AngularJS-ng      更新时间:2023-09-26

我正在表单的select元素中设置ng更改指令,但当我更改值时,不会调用链接到它的函数。我一直在阅读非常相似的问题,并应用我看到的答案,但到目前为止还没有一个奏效。

你能看出我做错了什么吗?

我的HTML:

<div class="row" ng-app="quoteApp">
    <div class="col-lg-12" ng-controller="QuoteController" ng-init="initialize()">
        <h1 class="page-header">Quote</h1>
                <div class="form-group">
                    <label>Carrier</label>
                    <select class="form-control" ng-model="form_carrier_id" ng-change="loadProducts()">
                        <option ng-repeat="carrier in carriers" value="{{carrier.id}}">{[{carrier.name}]}</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Product</label>
                    <select class="form-control" ng-model="form_product_id">
                        <option value=""></option>
                        <option ng-repeat="product in products" value="{{product.id}}">{[{product.name}]}</option>
                    </select>
                </div>
    </div>
</div>

我的控制器:

angular.module('quoteApp', ['angular-loading-bar']).config(function($interpolateProvider){
    $interpolateProvider.startSymbol('{[{').endSymbol('}]}');
})
    .controller('QuoteController', function ($scope, $http) {
        $scope.carriers = [];
        $scope.products = [];
        $scope.form_carrier_id = '';
        $scope.form_product_id = '';
        $scope.getUrl = function(action){return '/admin/application/quote/json?action='+ action;}
        $scope.initialize = function(){
            // Get the list of carriers
            $http.get($scope.getUrl('getCarriers'))
                .success(function (data) {
                    $scope.carriers = data;
                })
                .error(function () {
                    alert('Error loading carriers');
                });
        }
        $scope.loadProducts = function(){
            alert('HERE');
        }
    });

对我来说,一切看起来都很好。你能看到我缺了什么吗?第一个选择正常加载,问题是当我更改其值时,函数loadProducts不会被激发。

感谢

这可能不是问题本身,但是您应该始终使用ng-options而不是<option ng-repeat>由于

,我过去看到过一些奇怪的行为

我发现了问题所在。这就是我填补空缺的方式。必须这样填写:

            <select class="form-control" ng-model="form_carrier_id"
                    ng-options='carrier.id as carrier.name for carrier in carriers'
                    ng-change="loadProducts()">
            </select>

尝试使用ng选项来重复select元素中的产品。您可以按如下方式使用ng选项:

<select class="form-control" ng-model="form_product_id"
                ng-options="product.id as product.name for product in products" ng-change="loadProducts()">
                    <option value="">Select color</option>
                </select>

不是因为产品是设置值,所以每当选择一个值作为ng模型时,loadProduct都应该触发