Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 试图从指令中的内部作用域监视外部作用域无效_Angularjs_Angularjs Directive_Angularjs Scope - Fatal编程技术网

Angularjs 试图从指令中的内部作用域监视外部作用域无效

Angularjs 试图从指令中的内部作用域监视外部作用域无效,angularjs,angularjs-directive,angularjs-scope,Angularjs,Angularjs Directive,Angularjs Scope,我在从指令中查看范围变量时遇到一些困难 我有一个控制器,其作用域变量为val: $scope.val = { name: "hello" }; 我有一个使用这个值的指令。因此,在这个控制器的视图中,我有以下几点: <custom-component custom-attribute="val"></custom-component> 这不会导致手表功能触发!我不确定是什么问题。我还尝试将超时放在指令链接函数中,以防出现一些对象复制问题(在scope.$watch下面)

我在从指令中查看范围变量时遇到一些困难

我有一个控制器,其作用域变量为val:

$scope.val = { name: "hello" };
我有一个使用这个值的指令。因此,在这个控制器的视图中,我有以下几点:

<custom-component custom-attribute="val"></custom-component>
这不会导致手表功能触发!我不确定是什么问题。我还尝试将超时放在指令链接函数中,以防出现一些对象复制问题(在scope.$watch下面):

这还是不行

编辑:


所以我发现,如果在我的控制器中,我在更新变量后调用$scope.$digest(),一切都正常。为什么我需要手动调用此函数?

因为您使用的是在角度上下文之外调用的setTimeout,所以您必须调用scope。$apply,有两种方法可以解决您的问题

1) 使用
范围。$apply()

2) 将函数包装为角度
$timeout

link: function(scope, elem, attr) {
    scope.$watch('customAttribute', function(val){ console.log(val); }
    $timeout(function(){
       console.log("Changed chart type name");
       scope.customAttribute.name="baz";
    },5000);
},

由于您使用的是在角度上下文之外调用的setTimeout,因此您必须调用scope.$apply,有两种方法可以解决您的问题

1) 使用
范围。$apply()

2) 将函数包装为角度
$timeout

link: function(scope, elem, attr) {
    scope.$watch('customAttribute', function(val){ console.log(val); }
    $timeout(function(){
       console.log("Changed chart type name");
       scope.customAttribute.name="baz";
    },5000);
},

使用与AngularJS等效的
$timeout
,而不是
setTimeout
。它在内部使用$scope.$apply。使用
setTimeout
,事情发生在“角度世界”之外,而您的应用程序并不知道它们

不要忘记将
$timeout
注入控制器:

.controller('MyCtrl', ['$timeout', function($timeout) {
...

}]);

使用与AngularJS等效的
$timeout
,而不是
setTimeout
。它在内部使用$scope.$apply。使用
setTimeout
,事情发生在“角度世界”之外,而您的应用程序并不知道它们

不要忘记将
$timeout
注入控制器:

.controller('MyCtrl', ['$timeout', function($timeout) {
...

}]);

下面的两个答案都是正确的你有什么问题?下面的两个答案都是正确的你有什么问题?
link: function(scope, elem, attr) {
    scope.$watch('customAttribute', function(val){ console.log(val); }
    $timeout(function(){
       console.log("Changed chart type name");
       scope.customAttribute.name="baz";
    },5000);
},
.controller('MyCtrl', ['$timeout', function($timeout) {
...

}]);