1
<!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???

Luozt
  • 569
  • 4
  • 8
  • 1
    You are redefining the alert passed into the directive inside your `link`. Doesn't make sense. Create a demo that includes the basic html and replicates your problem. Also doesn't make sense that your controller can't use a function that is defined within it except that you are overwriting it if it is also beeing passed into the link – charlietfl Jan 04 '16 at 07:05
  • What are you trying to accomplish with this? I think what you should be using is custom scope events with `$on` and `$emit` instead if trying to two-way bind with function objects. – georgeawg Jan 04 '16 at 07:30

1 Answers1

0

After my practise these months, it'd better to provide a callback in the directive to the outside component because the directives must be completely compiled if it invokes the callback providing by itself.

(My English is poor! Can you understant?)

Luozt
  • 569
  • 4
  • 8