AngularJS: $watch for a select input

前端 未结 2 874
太阳男子
太阳男子 2021-01-20 14:52

I know we can use ng-change to solve this but I would like to understand why $watch doesn\'twork on select. Maybe I\'m doingsomething wrong but it seems I am not the only on

2条回答
  •  耶瑟儿~
    2021-01-20 15:25

    For make it working you need to do number of changes in your code, You need to put all server related information to one object named as self.serverInfo that will contain the information about server & servers directly bind this with scope variable will update binding automatically as per JavaScript Prototypal inheritance.

    HTML

    
      

    Controller

    var app = angular.module('app',[]);
    
    app.controller('SettingsCtrl', function ($scope, $log, serverSelection) {
    
        //List of servers to connect to
        $scope.serverInfo= serverSelection.serverInfo;
        $scope.$watch('serverInfo.server', function(NewValue, OldValue) {
            $scope.url = $scope.serverInfo.server.url;
        }, true);
    
    })
    
    app.service("serverSelection", function() {
        var self = this;
        self.serverInfo = {};
        self.serverInfo.servers = [
            { label: 'Production', value: 1, url: 'url1' },
            { label: 'Training', value: 2, url: 'url2' },
            { label: 'Local', value: 3, url: 'url2' }
        ];
    
        self.serverInfo.server = self.serverInfo.servers[1];
        console.log(self.server);
        self.serverInfo.url = self.serverInfo.server.url;
    
    })
    

    Working Plunkr

提交回复
热议问题