Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a controller which loads data from my API. Unfortunately I have a scenario where I cannot use a resolve to load the data.

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

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

My controller's template then uses a directive which 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 runs, the API has not yet returned with the data, and so $scope.formData is undefined when accessed.

Is there a way I can elegantly somehow make my directive only begin acting on the data when it becomes available? I can think of a couple solutions, but I'm not super happy with any:

  1. Broadcast an event indicating data is loaded.
  2. Put a $watch in place in the directive and then unbind the watch when the watch callback runs.
like image 348
Chad Johnson Avatar asked Apr 09 '15 19:04

Chad Johnson


1 Answers

Leave formData falsey (null/undefined works) until the data loads and use an ng-if. The directive only will compile once ng-if is true.

<form-component ng-if="myController.formData" form-data="myController.formData"></form-component>
like image 58
Dylan Watt Avatar answered Sep 29 '22 11:09

Dylan Watt