What is the best alternative for $ scope. $ Watch?

I am looking for an optimal solution to avoid use $scope.$watch, given the following use case:

1) directiveAhas the following scope:

{ sharedModel : '=' }

2) for your own use, directiveAyou need to change your internal variable with a name modelAbased on sharedModel.

3) directiveBuses directiveAand binds sharedModelto modelB(its internal model).

<directive-a
  shared-model="vm.modelB" />

4) When modelB/ changes sharedModel, I would like it to be modelAupdated (remember, the modelAdata is obtained only from sharedModel).

To execute # 4, I could add $scope.$watchin sharedModel. However, it $watchis expensive and not amenable to testing. Any recommendations best?

EDIT:

for an example with live code see jsfiddle . note the $scope.$watchline # 10 that I want to replace.

+4
source share
1 answer

In this case, this can be done without additional expensive hours. You can use the old good ES5 getters property , it will be very effective. So instead $watchtry something like this:

Object.defineProperty($scope, 'modelA', {
    get() {
        return $scope.sharedModel * 10;
    }
});

Demo: http://jsfiddle.net/mggc611e/2/

+4
source

Source: https://habr.com/ru/post/1610141/


All Articles