Question

I have a directive which needs to call functions from the Main controller but everytime i try to reference a function inside the directive nothing happens because it's undefined. When I access a value for instance $scope.someProp I do get the desired response but not when I call the function.

Anyone else who's faced this issue? Any Suggestions?

Was it helpful?

Solution

Few things:

  • Your controller exposes startChange function on the scope, so you need to call it on the scope, i.e. 'scope.startChange()' from within the directive and not 'startChange()'
  • Your confirmation directive uses isolate scope which is great if you know what youre doing, but in essence it is cutting you off from the parents scope on which you are trying to call a function

You got 3 options in this case

  1. Use Scope $emit/$broadcast to share state
  2. use isolate scope and '&' syntax to execute an expression in the context of parent scope -- example http://plnkr.co/edit/8UEDpoS6ie5qtFc8e08h?p=preview
  3. not use isolate scope and execute the startChange function on the scope of the directive which is the same as scope of the controller -- example: http://plnkr.co/edit/h1T2QNOL7wGNG0eprLMC?p=preview

OTHER TIPS

If you can change values, why not have your controller watch those values and run the function you need when they change?

$scope.$watch('myScopeVar', function(newValue, oldValue){
    if(oldValue !== newValue){
        $scope.someFunction();
    }
});

I'm not saying this is the best way to do this, but it should work. Beware of scope issues though. If your directive uses an isolated scope you may have to do this with a service that the directive changes the value in the service and the controller watches that service value as above. Again, not ideal, but should work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top