0

I'm creating my first directive and I'm running into some strange behaviour. The console.log() in my link-function is called twice. I've googled for some solutions, but I don't see how I need to change my code to change the behaviour...

My index.html:

<html>
<head>
  <title>GCSE Directive TEST</title>
</head>
<body ng-app="gcseTest">

  <google-image-search query="Test query"></google-image-search>

  <!-- Scripts -->
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
  <script src="gcse-directive.js"></script>
</body>
</html>

gcse-directive:

angular.module('gcseTest', [])
  .directive('googleImageSearch', [ function(){
      return {
        scope: {
          query: '@'
        },
        templateUrl: 'gcse-popup.html',
        restrict: 'E',
        replace: true,
        link: function ($scope, $element, $attrs) {
          $scope.search = function(){
            console.log("Gebruik query in link-functie: " + $scope.query);
            return "Gebruik query via popup: " + $scope.query;
          }
        }
      };
  }]);

gcse-popup.html:

<div>
  <h1>Directive Test</h1>
  {{search(query)}}
</div>

Can somebody explain what is going on here?

1 Answer 1

1

Your directive link function isn't getting called twice, its search function is getting called twice. The reason behind it is getting called twice as, you have used search function directly as in view bindings, so whenever digest cycle run your view binding gets evaluated. In this case digest cycle gets ran twice, that's why your search function ran twice and you can see console printed twice.

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

3 Comments

Thanks for your answer. Can you also explain to me what the best practice is to implement what I want to do (= show the result of a function in "link" directly in the view bindings)?
@bits can you explain your whole scenario? So that I can suggest correct way of doing it..
In my app, I want a button which opens a popup with results from google custom search engine (based on a value in the parent's controller. Once the user clicks on one of the results, the url is written to the parent's controller and shown in a textbox. The the popup must be reusable, so I wanted to put this in a directive. The button and textbox are in the directive's parent (unless you advise otherwise :)). In my code above, I'm only starting with my directive, so it does not (yet) do what I've described here:)

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.