2

for some reason I can't get working $watch for dynamically changing array

$scope.a1 = 1;
$scope.a2 = 2;

$scope.q = [$scope.a1, $scope.a2];
$scope.$watch('q', function(newVal) {
  alert(newVal);
}, true);

nothing happened on change. Bug I get alert on the initialization.

http://jsfiddle.net/qwertmax/FtLH8/

this it just example of my project where I have to "watch" number of values (input fields). That fields generated automatically by json request.

So, I heed help with dynamically add values to "$watching"

1
  • Fixed: jsfiddle.net/H8JLr, you lost your reference when you can the value of a1 and a2 Commented Dec 25, 2013 at 21:24

3 Answers 3

2

This is how I would solve this problem:

Since you will get the fields automatically generated I assumed you get an array of possible inputs back. Then you can automatically create the input fields and bind them. You can then watch that array. Something along the lines of this:

function TodoCtrl($scope) {
    $scope.inputs = [{
        label: "First Input",
        value: "Default Value"
    }, {
        label: "First Input",
        value: "Default Value"
    }]
    $scope.$watch("inputs", function (newVal) {
        alert("Changed an input");
    }, true);
}

The HTML:

 <div ng-repeat="inpt in inputs">
     <label>{{inpt.label}}</label>
     <input type="text" ng-model="inpt.value">
 </div>
Sign up to request clarification or add additional context in comments.

2 Comments

thank for the answer, but the trick is in the push new values into inputs array after initialization.
This is dynamic. Perhaps I am not understanding what you want? Check out this fiddle: jsfiddle.net/FtLH8/1 Is that what you meant? (The timeout is meant to simulate a possible HTTP Request)
1

Problem is that placing the variables in an array does not create a reference to the original variable since the originals are primitives. Thus your array never changes in your demo and the values you first place in it, remain the same when you update the variable that ng-model is bound to

You could bind ng-model to the array instead (ie ng-model=q[0]) but with angular is always a good rule to have a dot in ng-model, which means you are using objects not primitives

This demo shows how your array never changes:

http://jsfiddle.net/FtLH8/6/

Comments

0

what about $scope.$watchCollection()?

http://docs.angularjs.org/api/ng.$rootScope.Scope

sounds like it would been made for it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.