select firing watch function twice

744 views
Skip to first unread message

007design

unread,
Feb 9, 2012, 5:50:58 PM2/9/12
to AngularJS
in the example below, when you change the value of the first select
field, the alert is triggered twice for some reason and the model of
the second select field is populated twice ([a,b,a,b] instead of just
[a,b])
i don't understand why it appears to be triggering the $watch function
twice.

thanks,
007

<script src="http://docs-next.angularjs.org/angular-0.10.6.min.js"></
script>

<div ng:app="MyApp">
<div ng:controller="CtrlA">
<select ng:options="l.name for l in list"
ng:model="selection">
<option value=""></option>
</select>
<select ng:options="l.name for l in myValues"
ng:model="selection2">
<option value=""></option>
</select>
Selection: {{selection.name}}
</div>
</div>


var appModule = angular.module('MyApp', []);
appModule
.value('MySelection',{name:''})
.value('MyList',[{name:'test1'},{name:'test2'}])
.value('MyOtherList',[
{name:'test1', values:[{name:'a'},{name:'b'}]},
{name:'test2', values:[{name:'c'},{name:'d'}]}
]);

function CtrlA($filter, MySelection, MyList, MyOtherList) {
var self = this;
self.list = MyList;
self.otherList = MyOtherList;
self.selection = MySelection;
self.myValues = $filter('filter')(self.otherList,
{name:'test1'}).values;

self.$watch('selection.name', function() {
if (self.selection.name != '') {
var x = $filter('filter')(self.otherList,self.selection);
alert(angular.toJson(self.selection));
self.myValues = x[0].values;
}
});
}
CtrlA.$inject = ['$filter','MySelection','MyList','MyOtherList'];

Vojta Jina

unread,
Feb 10, 2012, 6:04:38 PM2/10/12
to ang...@googlegroups.com
I think I already refactored this example here https://groups.google.com/forum/?fromgroups#!topic/angular/Du9x5ABru_s

Anyway, even this code does fire only once for me:

Btw, please send jsfiddle or something like this next time, it saves us a lot of time...

V.

007design

unread,
Feb 10, 2012, 8:59:29 PM2/10/12
to AngularJS
thanks very much for your response. i only posted the code here as
jsfiddle was 'moving into the cloud at the time.
007

On Feb 10, 5:04 pm, Vojta Jina <vojta.j...@gmail.com> wrote:
> I think I already refactored this example
> herehttps://groups.google.com/forum/?fromgroups#!topic/angular/Du9x5ABru_s
Reply all
Reply to author
Forward
0 new messages