Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular directive link function called twice

In my angular app, directives are working fine during the first visit, but once a page been visited twice, all the directive link function gets called twice too. Say I am on page A, click a link to go to page B and then back to page A, all directives on page A will execute the their link function twice. if I refresh the browser it will become normal again.

Here is an example where the console.log will output twice when the second visit.

  @app.directive 'testChart', ["SalesOrder", (SalesOrder) ->
    return {
      scope: {options: '='}
      link: (scope, elem, attrs) ->
        console.log("............checking")
        SalesOrder.chart_data (data) ->
          Morris.Line
            element: "dash-sales"
            data: data
            xkey: 'purchased_at'
            ykeys: ['total']
            labels: ['Series a']
    }
  ]

Any idea?

Update

My Route

when("/dash", { templateUrl: "<%= asset_path('app/views/pages/dash.html') %>", controller: DashCtrl }).

so my chart is duplicated enter image description here

like image 237
user1883793 Avatar asked Jan 10 '14 08:01

user1883793


People also ask

What is restrict option in directive?

Directive comes with many Directive Definition Objects (DDO). From them restrict is one. Using restrict option inside a Custom Directive we can prevent the access level of Directive for Element(E), Attribute(A), Comment(M) or Class(C).

What is attrs in AngularJS?

scope is an AngularJS scope object. element is the jqLite-wrapped element that this directive matches. attrs is a hash object with key-value pairs of normalized attribute names and their corresponding attribute values. controller is the directive's required controller instance(s) or its own controller (if any).

What does$ compile do in AngularJS?

Overview. Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together. The compilation is a process of walking the DOM tree and matching DOM elements to directives. Note: This document is an in-depth reference of all directive options.

What is Link function in AngularJS directive?

link function is basically used to manipulate the DOM( Document Object Model ) element using custom directive. link option in custom directive registers DOM listener and also update the DOM.


1 Answers

also make sure you are not including your directive in your index.html TWICE!

like image 65
pleerock Avatar answered Oct 12 '22 13:10

pleerock