我有一個current-time
指令使用$timeout
,它似乎是在一個單獨的控制器調用函數。我很困惑這是爲什麼,我以爲控制器包含自己的範圍和相互分離?
基本上,myFunction
被當currentTime
指令$timeout
時調用。這是一件大事嗎?這會對我造成麻煩嗎?有人可以幫我理解這種行爲嗎?這是一個plunker,演示了我正在談論的行爲。
這裏是我的HTML
:
<html ng-app="myapp">
<head> <!-- using Angular version 1.2.0-rc3 --> </head>
<body>
<div ng-controller="TimeController">
<span current-time></span>
</div>
<div ng-controller="MyController">
<span class="grrr">{{myFunction()}}</span>
</div>
</body>
</html>
我的角度代碼:
var myapp = angular.module('myapp', []);
// just to show that I'm using my currentTime directive in separate controller.
// but it still happens if remove TimeController.
myapp.controller('TimeController', ['$scope', function($scope) {
console.log('entering TimeController');
}]);
myapp.controller('MyController', ['$scope', function($scope) {
$scope.myFunction = function() {
console.log('calling myFunction');
return 'myFunction was last called @ ' + new Date().toString();
};
}]);
// continuous update for time
myapp.directive('currentTime', ['$timeout', function($timeout) {
return function(scope,element,attrs) {
function updateTime() {
$timeout(function() {
element.text(new Date().toString());
updateTime();
}, 1000);
};
console.log('start clock');
updateTime();
};
}]);
太棒了,現在有道理。謝謝! – fbynite