Reputation: 113
I have a multi-page AngularJS web application that serves as an analytics dashboard. I am currently using $scope to create variables so I can display some of the data dynamically on the HTML pages. Instead of creating $scope variables that will be global no matter what page a user is visiting I would like to limit the variables to their page and their page only. Since I am new to Angular I have no idea how to do this. Any ideas on what I can do?
Upvotes: 0
Views: 1391
Reputation: 1606
Yes, you need to invoke the controllerAs syntax. Whether you do this in your routing or in your HTML elements is not relevant. But this allows you to use namespacing in Angular. In the following example I'm assuming you're invoking the ng-controller directive on your HTML elements.
Your HTML would be:
<div ng-controller="MyController as my">
{{my.var}}
</div>
And your controller would be
.controller("MyController", function() {
this.var = "hello world";
}
This has been implemented since Angular 1.3.X, if I'm correct. $scope is in fact polluting since it adds to the prototypical inheritance chain controllers use. I.e. child controllers do inherit $scope variables from their parents.
Upvotes: 0
Reputation: 1579
Your $scope
is based on the controller, so to make stuff specific to a page do something like this:
var app = angular.module('app', []);
app.controller('pageOne', ['$scope', function ($scope) {
$scope.forThis = "value for page one controller";
}]);
app.controller('pageTwo', ['$scope', function ($scope) {
$scope.forThis = "value for page two controller";
}]);
Upvotes: 1
Reputation: 1485
Create seperate controller for each page. $scope in nt global. Its scope is limited to its controller
Upvotes: 1
Reputation: 5448
$scope variables aren't global; they are specific to the controller. If you want variables that are specific to each page, put a controller on each page (and don't add a controller to a parent element since its scope will be inherited).
Upvotes: 4