<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>test directive</title>
</head>
<body ng-controller="bodyController">
<hello alert="outAlert"></hello>
<script type="text/javascript" src="http://cdn.bootcss.com/angular.js/1.4.8/angular.js"></script>
<script type="text/javascript">
angular.module("myApp", [])
.directive("hello", function(){
return {
scope: {
alert: "="
},
link: function(scope, elem, attrs){
scope.alert = function(msg){
window.alert(msg)
}
}
}
})
.controller("bodyController", function($scope, $timeout){
$scope.outAlert("this occurs an error: undefined is not a function")
$timeout(function(){
$scope.outAlert("this works great!")
}, 100)
})
</script>
</body>
</html>
如上面的代码所示,hello
指令将outAlert
函数转移到bodyController
。但是bodyController
不能立即使用outAlert
,否则会出现错误&#34; undefined不是函数&#34;。
所以我必须在100ms后运行它。但它看起来不像是一个正式的解决方案。我想寻求更好的方式!
我怎么能知道指令已完全编译在angularjs ???