<!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>
As above code, hello
directive transfers outAlert
function to bodyController
. But bodyController
can not use outAlert
immediately or it will occur an error "undefined is not a function".
So I have to run it after 100ms. But it doesn't look like a formal solution. I want to seek for a better way!
How I can know directive has been completely compiled in angularjs???