简体   繁体   English

AngularJS $scope.$watch 选择输入的属性 ngModel

[英]AngularJS $scope.$watch a property ngModel of a select input

I've an AngularJS app with a form generated by a python backend.我有一个由 py​​thon 后端生成的表单的 AngularJS 应用程序。 My problem is to trigger a specific function (listener) when the ngModel of a select input change:我的问题是在选择输入的 ngModel 更改时触发特定功能(侦听器):

here the rendered html code:这里呈现的 html 代码:

<select id="id_vehicle" name="vehicle" ng-model="contract.vehicle" class="ng-valid ng-valid-parse ng-dirty ng-touched">
    <option value="" selected="selected">---------</option>
    <option value="1">Qashqai</option>
    <option value="2">X6</option>
</select>

here my Angular code:这是我的 Angular 代码:

contract_form_app.controller("mainCtrl", ['$scope', '$http', '$location', '$window', 'djangoForm', function($scope, $http, $location, $window, djangoForm) {

$scope.contract = {
    vehicle: ""
};

function loadVehicleInformation(oldValue, newValue) {
    // This only triggered one time !!!!.
    console.log("Selected vehicle " + $scope.contract.vehicle);
};

$scope.$watch('contract.vehicle', loadVehicleInformation());

When I select another option on my select input, my listener function doesn't trigger... why?当我在选择输入上选择另一个选项时,我的侦听器功能不会触发......为什么?

ps: When the page has been loaded, the contract object will have a lot of others fields. ps:页面加载完成后,contract 对象会有很多其他字段。

I recommend you use ng-change instead of a watch on the controller if you're looking to trigger a function when that value changes, that's what ng-change is for.如果您希望在该值更改时触发功能,我建议您使用ng-change而不是控制器上的手表,这就是ng-change的用途。

<select id="id_vehicle" name="vehicle" ng-change="loadVehicleInformation()" ng-model="contract.vehicle" class="ng-valid ng-valid-parse ng-dirty ng-touched">
    <option value="" selected="selected">---------</option>
    <option value="1">Qashqai</option>
    <option value="2">X6</option>
</select>

有什么办法可以使用手表吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM