gpt4 book ai didi

Angularjs 在 $routeProvider 的 resolve 之后添加 $scope.$watch

转载 作者:行者123 更新时间:2023-12-02 03:37:25 24 4
gpt4 key购买 nike

我遇到了一个问题,我在解析完成后试图从我的范围中观察某个元素。出于某种原因,当我运行此代码段的第二行时它会运行,但我似乎无法在“解决”期间添加此 $watch。

我知道 promises 是异步的,但我怎么知道我什么时候决定添加 watch ?

variableToWatch 可以通过代码或在 UI 中更改(否则我只会使用 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;
}
);
};

最佳答案

更新:

如果您只想在初始值设置后 更改 时运行您的代码,您可以使用 watchFunc 的第二种形式作为第二个参数传递给$scope.$watch:

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

我没有完全理解这个问题,但我怀疑你想看值 $route.current.locals.data.initialValue 而不是 $scope.varibleToWatch?

在这种情况下,您可以使用 $scope.$watch 的替代形式,将 function 作为第一个参数:

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

或者,如果您想查看 $scope 上的变量,该变量由 $route.current.local.data.initialValue 中包含的字符串引用,那么你可以使用这个:

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

这是否解决了您的问题?

关于Angularjs 在 $routeProvider 的 resolve 之后添加 $scope.$watch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22516946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com