【发布时间】:2016-01-04 06:51:22
【问题描述】:
<!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,否则会出现“undefined is not a function”的错误。
所以我必须在 100 毫秒后运行它。但它看起来不像一个正式的解决方案。我想寻求更好的方法!
我怎么知道指令已经完全编译在 angularjs 中???
【问题讨论】:
-
您正在重新定义传递给
link内指令的警报。没有意义。创建一个包含基本 html 并复制您的问题的演示。你的控制器不能使用其中定义的函数也没有任何意义,除非你正在覆盖它,如果它也被传递到链接中 -
你想用这个来完成什么?我认为您应该使用
$on和$emit的自定义范围事件,而不是尝试与函数对象进行双向绑定。
标签: angularjs directive compiled