Reputation: 747
I have a custom directive that looks like this:
<menu-section sections="menu.sections" addons="addons"
options="options" menu="menu.id"></menu-section>
I've defined it here like this:
adminApp.directive("menuSection", ["$addons", function($addons) {
var sectionController = function($scope) {
console.log($scope);
console.log($scope.sections);
// Some $scope level functions defined here.
};
return {
restrict: "E",
scope: {
sections: "=",
options: "=",
menu: "=",
addons: "="
},
controller: sectionController,
templateUrl: "/template/menus/menu-section.html"
}
}]);
In the template I have a select element.
<div ng-repeat="section in sections">
<select ng-model="section.current_addon_ids" ng-options="addon.id as addon.name for addon in addons track by addon.id"></select>
My problem is that the current_addon_ids doesn't seem to be set. The select is filling up fine but current_addon_ids is undefined. In the console.logs above $scope returns a sections array. However, the next line returns an "undefined" to the console.
Is there some kind of weird timing issue going on here? It seems completely bizarre that I can see the section array in the $scope variable in one statement but in the next it is undefined.
Update:
I've figured out what is going on. Just not sure how to fix it.
In the Page Controller, the Menu is being set by getting a JSON structure from an Ajax call. That is where the Sections are being set on the Menu. However, the Directive Controller is running before the Ajax call comes back with a response. So when I attempt to access that property it is undefined.
Upvotes: 0
Views: 75
Reputation: 747
The solution I went with was to re-evaluate whether I had put too much into a single directive. I removed this directive and made several smaller ones. In the parent scope I could then use async.series() and collect the bits of the remote data in a bit more controlled way.
Thanks for the comments and helpful suggestions.
Upvotes: 0
Reputation: 2862
As per your updated question, I think you can use ng-if
for your custom directive when the ajax is returned successfully you can make it show . Though i'm unaware of your page controller whether your using service/factory for ajax below would be similar.
Template
<menu-section ng-if="" sections="menu.sections" addons="addons"
options="options" menu="menu.id"></menu-section>
controller
app.controller('pageController',['$scope','ajaxService',function($scope,ajaxService){
$scope.sections = [];
$scope.showMenuDirective = false; // initially directive is not shown
//get data or $http here itself , i thought u have use some service to do this
ajaxService.getData.then(function(data){
$scope.sections.push(data);
$scope.showMenuDirective = true; // directive shown here on success
});
}]);
Upvotes: 1