How to detect change in model for multidimensional array in angular js - angularjs

I want to fire an event when my multidimensional scope variable get changed i.e. element added, removed etc. I tried to do so using $scope.$watch and $scope.$watchCollection, but its not working.
This is the scenario.
$scope.variable=[{ID:1,text:'abc'},{ID:1,text:'abc'}];
$scope.content='';
$scope.$watch('$scope.variable',function(){
$scope.content=$scope.variable[0].text;
});
Any help ?

add true as an argument
$scope.$watch('variable',function(){
$scope.content=$scope.variable[0].text;
}, true);
NB: no need for $scope in argument

Related

TyperError: Cannot read property 'length' of undefined

Our team is using angularjs to develop a ServiceNow widget and we are seeing "TyperError: Cannot read property 'length' of undefined" in our console:
When we click on "at eval", it takes us to this particular snippet of code with line 321 highlighted:
We can't seem to figure out what's causing that error. We are using $watch on an array ($scope.data.list) and have read that $watchCollection might be better, but we tried that with no change. Any ideas what could be causing this error and how to get rid of it?
From the code you have posted, you haven't defined or nor declared
$scope.data.list (I'm assuming $scope.data is defined somewhere). To
resolve that, you need to at least declare your $scope.data.list first to watch over it.
Coming to the $watch part, it depends on what your requirement is.
$scope.$watchCollection looks for changes made in the array as well as elements whereas,
$scope.$watch will only look for changes made if the array is totally
assigned to a different one. Otherwise, if you want to watch deep, you can
use $scope.$watch with a boolean true variable passed as a third
argument to it.
Refer this link for the full documentation - https://www.sitepoint.com/mastering-watch-angularjs/
As of my knowledge $watch on $scope.data.list called whenever any value changed in this collection
So by looking at error it seems like $scope.data.list list in no longer exits in $scope.data. Try to find out where $scope.data is going to change.
And use below syntax for watch on collection
$scope.$watchCollection('names', function(newList,oldList) {
if(newList && newList.length) {
$scope.data.list = newList.length;
}
});

django-autocomplete-light and angular: how can angular get the value selected

Using django-automcomplete-light V3 and angular on a non admin page.
Using the widget autocomplete.ModelSelect2
Where is the selected value stored? Using firebug, it's not in a new hidden html element and if i attempt to watch the original (now hidden) select element, it's value never changes if I change the selected value in the autocomplete widget.
How can angular watch/read this value?
Update:
As #visegan below points out you can use jquery syntax to get the value but for some reason you can't watch it.
i.e. this watch never gets triggered:
$scope.$watch(function(){
return $('#id_field').val();
},
function(newVal, oldVal){
console.log('current %r', newVal);
$scope.models.foo=parseInt(newVal);
});
Well I have just tried with my project and it was pretty straight forward:
$('#id_field').val()
To be honest, I am also not sure where exactly does the value come from.
As for the change watcher: autocomplete light now uses select2 component, which is apparently a bit problematic with angular.
There are two approaches that works: first one is to add more jquery:
$('#id_field').change(function() {alert('changed')});
This I have tested. The other approach is to do it somehow natively. Look at Select2 event handling with Angular js

unable to update controller model value from custom directive with controller as syntax

I am facing problem to update my model values from custom directive using controller as syntax. I can clearly see that through console.log that the values are getting changed in the directive however they are not getting updated in the controller. <h4>{{self.tabs}} </h4> always shows same values.
In addition I want to do watch on controller (self --> tabs) model to add 'active class' but when I try to use watch it is throwing me out error. So I have commented that part. The following is the watch related code, which is not working:
$scope.$watch('tabsCtrlself.tabs.index', function() {
if (tabsCtrlself.tabs.index === index) {
angular.element($element).addClass('active');
}
});
Please find my plunker, Can any one direct me to fix this?
you can use 'ng-class' attribute,eg:
<en-tab data-pane="myPaneName1" ng-class="{active:index==1}">Tab #1</en-tab>
<en-tab data-pane="myPaneName2" ng-class="{active:index==2}" >Tab #2</en-tab>
<en-tab data-pane="myPaneName3" ng-class="{active:index==3}">Tab #3</en-tab>
'index' is a object in angular: $scope.index, initializes its value:
$scope.index=1;
The first item is selected by default.
I think the object of 'tabsCtrl.tabs.index' is not a angular object, so can't auto refresh

Watch form model for changes

Assuming a given form such as <form name="myForm">, it's easy enough to watch for validity, error, dirty state, etc. using a simple watch:
$scope.$watch('myForm.$valid', function() {
console.log('form is valid? ', $scope.myForm.$valid);
});
However, there doesn't appear to be an easy way to watch if any given input in this form has changed. Deep watching like so, does not work:
$scope.$watch('myForm', function() {
console.log('an input has changed'); //this will never fire
}, true);
$watchCollection only goes one level deep, which means I would have to create a new watch for every input. Not ideal.
What is an elegant way to watch a form for changes on any input without having to resort to multiple watches, or placing ng-change on each input?
Concerning the possible duplicate and your comment:
The directive solution in that question works, but it's not what I had in mind (i.e. not elegant, since it requires blur in order to work).
It works if you add true as third parameter for your $watch:
$scope.$watch('myFormdata', function() {
console.log('form model has been changed');
}, true);
Further information see the docs.
Working Fiddle (check console log)
Another more angular way would be to use angular's $pristine. This boolean property will be set to false once you manipulate the form model:
Fiddle
Based on my experience with my forms (new dev, but working with Angular for a while now), the elegant way to watch a form for changes is actually not to use any type of watch statement at all actually.
Use the built-in Angular boolean $pristine or $dirty and those values will change automatically on any input field or checkbox.
The catch is: it will not change the value if you add or splice from an array which had me stumped for a while.
The best fix for me was to manually do $scope.MyForm.$setDirty(); whenever I was adding or removing from my different arrays.
Worked like a charm!

$watch not being triggered on array change

I'm trying to figure out why my $watch isn't being triggered. This is a snippet from the relevant controller:
$scope.$watch('tasks', function (newValue, oldValue) {
//do some stuff
//only enters here once
//newValue and oldValue are equal at that point
});
$scope.tasks = tasksService.tasks();
$scope.addTask = function (taskCreationString) {
tasksService.addTask(taskCreationString);//modifies tasks array
};
On my view, tasks is clearly being updated correctly as I have its length bound like so:
<span>There are {{tasks.length}} total tasks</span>
What am I missing?
Try $watch('tasks.length', ...) or $watch('tasks', function(...) { ... }, true).
By default, $watch does not check for object equality, but just for reference. So, $watch('tasks', ...) will always simply return the same array reference, which isn't changing.
Update: Angular v1.1.4 adds a $watchCollection() method to handle this case:
Shallow watches the properties of an object and fires whenever any of the properties change (for arrays this implies watching the array items, for object maps this implies watching the properties). If a change is detected the listener callback is fired.
Very good answer by #Mark. In addition to his answer, there is one important functionality of $watch function you should be aware of.
With the $watch function declaration as follows:
$watch(watch_expression, listener, objectEquality)
The $watch listener function is called only when the value from the current watch expression (in your case it is 'tasks') and the previous call to watch expression are not equal. Angular saves the value of the object for later comparison. Because of that, watching complex options will have disadvantageous memory and performance implications. Basically the simpler watch expression value the better.
I would recommend trying
$scope.$watch('tasks | json', ...)
That will catch all changes to the tasks array, as it compares the serialized array as a string.
For one dimensional arrays you may use $watchCollection
$scope.names = ['igor', 'matias', 'misko', 'james'];
$scope.dataCount = 4;
$scope.$watchCollection('names', function(newNames, oldNames) {
$scope.dataCount = newNames.length;
});

Resources