The controller must wait for the Directive to load
I am currently writing a small set of AngularJS controls and I am facing a problem here. The control I am creating is a button (let's start simple).
The directive looks like this:
officeButton.directive('officeButton', function() {
return {
restrict: 'E',
replace: false,
scope: {
isDefault: '@',
isDisabled: '@',
control: '=',
label: '@'
},
template: '<div class="button-wrapper" data-ng-click="onClick()">' +
'<a href="#" class="button normal-button">' +
'<span>{{label}}</span>' +
'</a>' +
'</div>',
controller: ['$scope', function($scope) {
// Controller code removed for clarity.
}],
link: function(scope, element, attributes, controller) {
// Link code removed for clarity.
}
}
});
I removed some code because it changes my question a lot and I don't think it is needed here.
Inside my controller
directive, I write an API and execute by executing the following code:
controller: ['$scope', function($scope) {
// Allows an API on the directive.
$scope.api = $scope.control || {};
$scope.api.changeLabel = function(label)
$scope.label = label;
}
}]
So, in my directive, I have an isolated area that I can pass a property to control
. Through this property, I will have access to the method changeLabel
.
My control can be rendered with the following directive on the HTML website:
<office-button control="buttonController"></office-button>
My app controller will look like this:
officeWebControlsApplication.controller('OfficeWebControlsController', ['$scope', function($scope) {
$scope.buttonController = {};
}]);
I can execute my method changeLabel
right now by calling the following method in myscope
$scope.buttonController.changeLabel('Demo');
However, this does not work as it is currently changeLabel
undefined. The button must be fully rendered first.
Any idea on how to fix this problem?
Edit: Added plunger
I added a plunker to provide more information. When the method changeLabel
is called inside the event onClick
then everything works, but if I go outside it doesn't work anymore. This is because the $ scope.api.changeLabel is not defined at runtime (the button is not visible yet). So I basically have to wait in the app controller until the button is fully rendered.
respectfully
source to share
No one has answered this question yet
Check out similar questions: