2013-07-11 25 views
1

我在观察指令中的示波器变量时遇到了一些困难。试图从指令中的内部示波器观察外部示波器不工作

我有一个范围可变称为VAL控制器:

$scope.val = { name: "hello" }; 

我有一个使用该值的指令。因此,在此控制器的观点我沿着线的东西:

<custom-component custom-attribute="val"></custom-component> 

我已经建立了具有范围的精细

var myDir = function() { 
    return { 
     restrict: 'E', 
     scope: { 
      customAttribute: '=customAttribute' 
     }, 
     link: function(scope, elem, attr) { 
      scope.$watch('customAttribute', function(val){ console.log(val); } 
     }, 
     replace: true, 
     template:'<div class="hello"></div>' 
    }; 
} 

手表功能火灾时,我第一次运行一个指令应用程序。现在我在我的控制器中放了一个暂停,并执行如下操作:

setTimeout(function(){ 
     console.log("Changed chart type name"); 
     $scope.customAttribute.name="baz"; 
    },5000); 

这不会导致监视功能触发!我不确定问题是什么。我也试图把超时的情况下,指令链接功能中有一些对象拷贝问题(下面范围$表。):

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

这仍然没有工作!

编辑:

所以,我已经发现,如果在我的控制器我调用$范围$摘要()更新变量一切正常后。为什么我需要手动调用此函数?

+0

这两个答案都正确与他们您有什么问题? http://docs.angularjs.org/api/ng.$timeout – shaunhusain

回答

3

由于您使用的setTimeout被称为角上下文之外,所以你必须调用范围。$应用,有两种方法可以解决你的问题

1)使用scope.$apply()

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

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); 
}, 
3

代替setTimeout的功能,使用$timeout,这是AngularJS的等价物。它使用$ scope。$内部应用。有了setTimeout,事情就发生在“角度世界”之外,你的应用程序不知道它们。

不要忘记注入$timeout到控制器中:下面

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

}]);