TAGS :Viewed: 6 - Published at: a few seconds ago

[ Write initialization function for directive in angularjs? ]

I am developing one directive for my grid control, and i need to get some common resource data from server before i build the grid control.

How i can write initialization function for the directive? I need it to execute before loading the control to DOM and it has to be something like lazy one(it should execute only when the DOM got directive).

I have written one function in the controller of directive to get the resource from server, but the directive execution is not waiting for the server response. it is just continuing the execution and throwing resource value is undefined.

Please anyone help to me solve this?

Answer 1


Either you could use the resolve function of your state to have the data loaded before the controller is instantiated at all, see https://docs.angularjs.org/api/ngRoute/provider/$routeProvider

Or you could do it the angular way and

  • initialize an empty array for your data in the controller
  • make the ajax request in the controller, and update the array when the response comes in
  • watch the array to update the dom. If you simply use ng-repeat to show the data, that watch will be set up automatically. If you do "manual" DOM manipulation you must use $scope.$watch() yourself.