$watch inside a service?

前端 未结 4 1259
轻奢々
轻奢々 2020-12-13 01:47

Is it possible to set up a $watch on an array of objects inside a service (I\'d like the $watch declaration itself to be inside the service)?

4条回答
  •  遥遥无期
    2020-12-13 02:08

    Can you clarify what you want to achieve? As I understand, you are getting an array of objects from the server as your model. Then it's not clear:

    1. Do you want to verify if some objects in the array have been changed (maybe since the last call to the server in case you do recurrent pooling)?
    2. Do you want to verify if some objects in the array have been changed by the user via some front-end control elements?

    In case 1, you don't really need to use $watch (or rather $watchCollection) but you should iterate through the array you received from the server and verify the changes (the same what $watchColleciton would do). In case the object is different to the one you currently hold - you call object.$save() on this element.

    In case 2, use $watchCollection() on the $scope passed as a parameter to your service function or use $rootScope if you hold your array in the $rootScope.

    I can provide you with real code if you would clarify the scenarios.

提交回复
热议问题