Can I pass a controller function to a variable in a function reference in a directive?

I am using a custom directive for angularjs and I want to pass some variables to the directive to build the directive with the data set, the data is received from the $ http response but it takes a long time and nothing happens when the variables are filled with the data response.

I think if I can make a request in a controller function inside a directive, maybe I can set a timeout function until the response is complete, but the questions are if I get the data in the $ http response and fill in by moving the variable with this data, can I pass it to the reference function?

EDIT: The end result is a bunch of fields on the form filling it in dynamically from a json object.

+3


source to share


2 answers


Typically, if you have any information that you want to expose with a custom directive , you do it using attributes manually or using isolate scope .

Imagine I had a specific directive to display some details about widget

, but I wanted it to be generic ... then I could write my directive like this:

{
   restrict: 'E',
   template: '<div>{{widget.name}}</div>',
   scope: {
      widget:'=' //Allows two way binding with parent scope
   }
}

      

This is the simplest possible use case, but it will allow me to bind to that object in my directive and isolate it completely.



Assuming I have a controller that is actually viewing my widget from a $ http call, I could do this:

<!-- 
    widget attribute is made available because of how we
    declared our directive definition.
-->
<widget-directive widget="ctrl.myWidget"></widget-directive>

      

If your directive is more advanced and you need to perform some action based on changes to this object, then you can simply view it in the link function :

link: function(scope, elem, attrs){
   scope.$watch('widget', function(newVal, oldVal){
      // 
      //Do something here now that 'widget' has changed
      //
   });
}

      

0


source


When you have to watch an object (deep clock), you can declare your clock like this:

link: function(scope, elem, attrs){
   scope.$watch(function () { return scope.widget; }, function(newVal, oldVal){
      scope.widget = newVal;
   }, true);
}

      



Notice the function that returns an object and the value true is added to the end of the clock.

0


source







All Articles