Pergunta

I'm having an issue where I am trying to watch a certain element from my scope after the resolve is done. For some reason, it gets run when i run the second line from this snippet and I dont seem to be able to add this $watch during the "resolve".

I understand that promises are asynch, but how can I know when my resolve is done to then add the watch?

The variableToWatch can be changed either by code or in the UI (otherwise i would've just used ng-change="doWork()")

    $scope.variableToWatch = $route.current.locals.data.initialValue;
    $scope.listOfDependantData = $route.current.locals.data.items;

    $scope.$watch('variableToWatch', function (newValue) {
        myService.getNewDependantData(newValue).$promise.then(
            function (items) {
                $scope.listOfDependantData = items;
            }
        );
    };
Foi útil?

Solução

Update:

If you want to run your code only when it changes after the initial setting of value, you can use the second form of the watchFunc passed as the second argument to $scope.$watch:

$scope.$watch('variableToWatch', function (newValue, oldValue) {
    if (typeof newValue !== 'undefined' && newValue !== oldValue) {
        // Use the new value here ...
    }
});

I don't fully follow the question, but I suspect that you want to watch the value $route.current.locals.data.initialValue instead of $scope.varibleToWatch?

In that case, you can use the alternate form of $scope.$watch with a function as the first argument:

$scope.$watch(function () { return $route.current.local.data.intialValue; }, function (newValue) {
    // ...
};

Or, if you want to watch the variable on your $scope which is referenced to by the sting contained in $route.current.local.data.initialValue, then you can use this:

$scope.$watch(function () { return $scope[$route.current.local.data.intialValue]; }, function (newValue) {
    // ...
};

Does this solve your problem?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top