0

I have a directive setup as follows:

angular.module("app", []).directive("myDirective", function(){

    return {

       scope: {},
       link: function($scope){

           $scope.myFunction = function(){
                //Do DOM manipulation
           }

       }

    }


});

and in my html I simply have

<div my-directive>
    <a href="" ng-click="myFunction()">Click Me</a>
</div>

when I click "Click Me" nothing prints to the console, HOWEVER, if I remove the scope property or change it to scope:true then it works as expected. I know this has to do with isolate scope but I don't fully understand what's going on. I want to have an isolate scope as this is going to be a modular directive I will use in many different project.

NOTE: I'm using angular 1.4.6

UPDATE: This function needs to do DOM manipulation. Which is why it's in the link function.

0

2 Answers 2

1

The reason this isn't working is because how link is being used.

Since the elements exist within the directive before it exists, those elements aren't compiled with the information inside link. To get what you want you need put those elements in template or templateUrl so that it can be compiled against link.

Here is an example:

angular.module("myApp", []).directive("myDirective", function() {
      return {
        scope: {},
        template: '<a href="" ng-click="myFunction()">Click Me {{value}}</a>',
        link: function(scope) {
          scope.value = 'Value here';
          scope.myFunction = function() {
            console.log('you are here.');
          }
        }
      }
    });
<script data-require="[email protected]" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
<div ng-app="myApp">
  <div my-directive>
    <a href="" ng-click="myFunction()">Click Me {{value}}</a>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

0

Put your function inside the controller of your directive. You don't event need to use $scope if you declare a controllerAs

JS:

angular.module("app", []).directive("myDirective", function(){

    return {
      restrict:'E',
       scope: {},
       template:'<div><a href="" ng-click="MyCtrl.myFunction()">Click Me</a></div>',
       controllerAs:'MyCtrl',
       controller: function(){
        this.myFunction = function(){
          alert('okok');
        }
      },
       link: function(scope, element, attrs){

       }

    }


});

HTML:

<body>
  <my-directive> </my-directive>
</body>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.