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-ponent form-data="myController.formData"></form-ponent>
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 bees available? I can think of a couple solutions, but I'm not super happy with any:
- Broadcast an event indicating data is loaded.
- Put a $watch in place in the directive and then unbind the watch when the watch callback runs.
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-ponent form-data="myController.formData"></form-ponent>
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 bees available? I can think of a couple solutions, but I'm not super happy with any:
- Broadcast an event indicating data is loaded.
- Put a $watch in place in the directive and then unbind the watch when the watch callback runs.
- 2 I doubt there is something more elegant than (2) as it stands, so I would go for it. – Nikos Paraskevopoulos Commented Apr 9, 2015 at 20:10
1 Answer
Reset to default 5Leave formData
falsey (null
/undefined
works) until the data loads and use an ng-if. The directive only will pile once ng-if is true.
<form-ponent ng-if="myController.formData" form-data="myController.formData"></form-ponent>