javascript - How can I make an Angular directive wait for isolate scope data to be available? -


i have controller loads data api. unfortunately have scenario cannot use resolve load data.

angular.module('myapp').controller('mycontroller', function() {     var mycontroller = this;      formservice.find('123').then(function(response) {         mycontroller.formdata = response.data;     }); }); 

my controller's template uses directive uses data:

<form-component form-data="mycontroller.formdata"></form-component> 

and directive:

angular.module('myapp').directive('formcomponent', function() {     'use strict';      return {         restrict: 'e',         scope: {             formdata: '=',         },         templateurl: 'formcomponent.html',         link: function($scope, element, attrs) {             // outputs "undefined" not yet loaded when             // directive runs.             console.log($scope.formdata);         }     }; }); 

as can see, when directive runs, api has not yet returned data, , $scope.formdata undefined when accessed.

is there way can elegantly somehow make directive begin acting on data when becomes available? can think of couple solutions, i'm not super happy any:

  1. broadcast event indicating data loaded.
  2. put $watch in place in directive , unbind watch when watch callback runs.

leave formdata falsey (null/undefined works) until data loads , use ng-if. directive compile once ng-if true.

<form-component ng-if="mycontroller.formdata" form-data="mycontroller.formdata"></form-component> 

Popular posts from this blog