Scoping issues here, I have a page that includes an ng-switch:
<div ng-switch on="pagename()">
<div ng-switch-when="plans">
<div ng-include="'/assets/angular/plans/existingplans.html'"></div>
</div>
<div ng-switch-when="new">
<div ng-include="'/assets/angular/plans/newplans.html'"></div>
</div>
<div ng-switch-when="credits">
<div ng-include="'/assets/angular/plans/creditspanel.html'"></div>
</div>
<div ng-switch-when="wizard">
<div ng-include="'/assets/angular/plans/wizard.html'"></div>
</div>
</div>
As you can see I switch on a method in the controller, this method is bound to a scope variable that has a RESTful data source attached:
$scope.pagename = function() {
var loc = $location.path().split("/").pop();
if (loc == "plans" && $scope.plansinfo.data.length < 1) {
return "wizard";
} else if (loc == "plans" && $scope.plansinfo.data.length >= 1) {
return "plans";
} else if (loc == "new") {
return "new";
} else if (loc == "wizard") {
return "wizard";
} else {
// alert(loc)
console.log(loc);
console.log(typeof $scope.plansinfo.data);
return "credits";
}
};
The basic idea being it drives the user to the correct page. The problem being whichever page you land on gets the $scope.plansinfo
datasource object attached to it, but then when you traverse pages the other pages have that object undefined.
So in a nutshell, what am I doing wrong in my controller so that the object is being created in the nested scope, not the top level scope?
Thanks
Tom
==== EDIT ====
In an attempt to clean things up I followed the suggestion below to move the code to a service but now all I get is:
TypeError: string is not a function
Here's my attempt:
.factory('PlansData', function() {
var data = {};
data.plansinfo = {};
return {
updateinfo: function(newdata) {
data.plansinfo = newdata;
},
pagename: function (location) {
return 'credits';
},
plansinfo: data
}
})
controller:
$scope.pagename = PlansData.pagename($location);
So it should just return the string, but instead I get the above error. What am I missing?
Thanks
Tom
This would be a good time to use services to manage your model data rather than a controller. You may have already used a service to manage your RESTful API so you could possibly include the pagename
function there. If not, here is an example of creating a new service to manage the data:
app.service('locService', function (){
this.pagename = function () {
// switch function here
};
});
Then you can inject that service into the controller that needs the info:
app.controller('myController', function (locService){
$scope.pagename = locService.pagename;
});