How can I make the Angular directive wait for data to be scoped?

I have a controller that loads data from my API. Unfortunately, I have a scenario where I cannot use the solution to load data.

angular.module('myApp').controller('myController', function() {
    var myController = this;

    formService.find('123').then(function(response) {
        myController.formData = response.data;
    });
});

My controller template uses a directive that uses this data:

<form-component form-data="myController.formData"></form-component>

And the directive:

angular.module('myApp').directive('formComponent', function() {
    'use strict';

    return {
        restrict: 'E',
        scope: {
            formData: '=',
        },
        templateUrl: 'formComponent.html',
        link: function($scope, element, attrs) {
            // Outputs "undefined" as this is not yet loaded when
            // this directive runs.
            console.log($scope.formData);
        }
    };
});

As you can see, when the directive starts, the API has not returned with data yet, and therefore when using access_formData is undefined.

Is there a way that I can elegantly somehow make my directive take effect only when it becomes available? I can come up with a couple of solutions, but I'm not very happy with any:

  • The transfer of data indicating the event will be downloaded.
  • Put $ watch in the directive, and then untie the watch when the callback works.
+4
1

formData falsey (null/undefined) , ng-if. ng-if true.

<form-component ng-if="myController.formData" form-data="myController.formData"></form-component>
+4

All Articles