Angularjs 如何在scope.watch中返回多个值?
我试图从$scope.watch函数返回多个值Angularjs 如何在scope.watch中返回多个值?,angularjs,angularjs-watch,Angularjs,Angularjs Watch,我试图从$scope.watch函数返回多个值 angular.module("MainApp") .directive('isActiveNav', [ '$location', function($location) { return { restrict: 'A', link: function($scope, el, attrs) { $scope.location = $location; $scope.$watch(function
angular.module("MainApp")
.directive('isActiveNav', [ '$location', function($location) {
return {
restrict: 'A',
link: function($scope, el, attrs) {
$scope.location = $location;
$scope.$watch(function() {
return (el.parent().parent().parent().parent().hasClass('cbp-small'),location.path());
}, function(hasClas, currentPath) {
setTimeout(function(){
console.log(hasClas, currentPath);
},0)
});
}
};
}]);
但是这给了我一个错误uncaughtsyntaxerror:strict模式之外还不支持块作用域声明(let、const、function、class)
我在这里尝试观察多个值:
1.应用程序的当前Url
2.如果某个元素有一个名为“cbp small”的类
我也尝试过$watchCollection和$watchGroup,但都无法使它们工作。因此,我试图从scope.watch func返回多个值 您可以连接值:
return el.parent().parent().parent().parent().hasClass('cbp-small').toString() + "&&&" + location.path();
然后将生成一个字符串,如“true&&&&&/…/…/”
Angular将脏检查此字符串,如果任何值将更改,则该字符串将更改,以便调用回调
在回调写中
function(newVal) {
var args = newVal.split('&&&');
var hasClas = args[0]==="true", currentPath = args[1];
setTimeout(function(){
console.log(hasClas, currentPath);
},0
});
第一个参数将不接受
()
语法中的两个值。相反,您希望将要监视和返回的两个值存储在对象或数组中
angular.module("MainApp")
.directive('isActiveNav', [ '$location', function($location) {
return {
restrict: 'A',
link: function($scope, el, attrs) {
$scope.location = $location;
$scope.$watch(
function() {
return {hasPath: el.parent().parent().parent().parent().hasClass('cbp-small'), currentPath: location.path()};
},
function(newPathObject, oldPathObject) {
if (!angular.equals(newPathObject, oldPathObject)) {
setTimeout(function(){
console.log(newPathObject.hasClass, newPathObject.currentPath);
},0)
};
},
true
});
}
};
}]);
您还需要添加true
作为objectEquality==true的第三个参数。根据:
当objectEquality==true时,watchExpression的不等式根据angular.equals函数确定。保存值
为便于以后比较,将使用angular.copy函数。
因此,这意味着观察复杂对象将产生不利影响
内存和性能影响
另外,在使用$watch时,您希望通过将对象包装在
if
语句中,并检查对象值是否已使用angular.equals
更改,防止对象实例化时触发回调。您可以使用来引用它。它每次都会调用callback,因为对象是通过引用存储的,dirtycheck将始终是passarray(对象:)),因此它也将起作用,您可以将true
作为$scope.$watch
的第三个参数传递给AngularJS,以使AngularJS使用angular.equals
而不是=
进行脏检查。我认为这个解决方案是最好的。第一次会的,但你们可以检查对象是否被修改过@stevuu啊,是的!!没错,我忘了真正的参数。你可以删除!如果使用true
参数,则等于
part,因为AngularJS会为您这样做。