1

I have a simple js array being retrieved by an angular factory, injected into a control, watched, then displayed in a table using ng-repeat from within a view state managed by ui-router.

Initially I attempted to subscribe to this array using $watchCollection...

self.$watchCollection( self.Data, function(newData, oldData){
  self.total = newData.length;
});

However this was only running when I initially load the app. I found that the only way to subscribe to the running collection was to use an anonymous function returning the array in question.

self.$watchCollection( function() { return self.Data }, function(newData, oldData){
  self.totalWatchedWithAnonFunc = newData.length;
})

View this all in http://plnkr.co/edit/L7mycl

From everything I read, all I should have needed to do for a valid subscription was to pass in the array itself and not an anonymous function that returns the array.

The reason I included ui-router is because my actual application is using it heavily and I wanted to mock up my environment as closely as possible to how I've got things set up.

What am I not understanding? Could I be doing something differently?

Thanks.

1

1 Answer 1

1

Are you looking for self.$watchCollection("Data", ...) instead of self.$watchCollection(self.Data, ...)? Try it out! See the docs to see why: the first argument is a string evaluated on the scope, or a function taking a scope that returns something you want to watch.

Sign up to request clarification or add additional context in comments.

2 Comments

The property name as a string?!?! I am stunned that this is the solution...and not even scoped? That's some crazy new territory...thanks for the speedy response.
It's a recurring thing in AngularJS to evaluate strings on the scope, things like ngRepeat, ngInit, ngInclude, et cetera et cetera, all take expressions that are evaluated on the current scope. It's a little odd compared to other languages/frameworks but when you get used to it, it's quite powerful!

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.