Angularjs: $watch For A Select Input
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 one to stru
Solution 1:
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
<bodyng-controller="SettingsCtrl"><divclass="list"><labelclass="item item-input item-select"><divclass="input-label">
Server
</div>
{{serverInfo}}
<selectng-model="serverInfo.server"ng-options="s as s.label for s in serverInfo.servers"></select></label></div></body>
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() {
varself = 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;
})
Solution 2:
I accept answer from @pankajparkar but I'd like to show my final code as in fact with the proper binding proposed by @pankajparkar I don't need a $watch anymore.
HTML
<divclass="list"><labelclass="item item-input item-select"><divclass="input-label">
Serveur
</div><selectng-model="serverSelection.server"ng-options="s as s.label for s in serverSelection.servers"></select></label></div><p>URL: {{serverSelection.server.url}}</p>
JS
.controller('SettingsCtrl', function ($scope, $log, serverSelection) {
//List of servers to connect to$scope.serverSelection= serverSelection;
})
.service("serverSelection", function() {
varself = this;
self.servers = [
{ label: 'Production', value: 1, url: 'url0' },
{ label: 'Training', value: 2, url: 'url1' },
{ label: 'Local', value: 3, url: 'url2' }
];
self.server = self.servers[1];
})
Post a Comment for "Angularjs: $watch For A Select Input"