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:
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>
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With