Tom
Tom

Reputation: 7740

Watch variable not on $scope to update a variable which is on $scope

I'm trying to create a mini-view within my ng-view by doing something like this:

<div ng-include="currentPage" />

And then my controller looks like this

var currentPageIndex = 0;
var pages = ['page1.html','page2.html'];

$scope.currentPage = pages[currentPageIndex];
$scope.nextPage = function() {
    currentPageIndex++;
}

The problem is that angular doesn't know when currentPageIndex changes.

So, I've tried putting currentPageIndex on the $scope, like $scope.currentPageIndex, but that still doesn't let angular know that $scope.currentPage should change.

As I'm writing this I'm thinking that maybe this (below) will work, but is it really the best solution?

$scope.$watch('$scope.currentPageIndex', function(value) {
    $scope.currentPage = pages[$scope.currentPageIndex];
});

Upvotes: 0

Views: 551

Answers (4)

Raymond Dumalaog
Raymond Dumalaog

Reputation: 353

$scope.$watch('currentPageIndex', function(value) {
    $scope.currentPage = pages[$scope.currentPageIndex];
});

I remove the the '$scope' then it worked for me.

Upvotes: 0

Joao Polo
Joao Polo

Reputation: 2163

You need to use a function to define ng-include page (at my example, I used uppercase PAGES to refer a constant):

$scope.getPage = function() {
    return PAGES[$scope.page];
}

and your include:

<div ng-include="getPage(page)"></div>

You can see me plunkr with a functional example:

http://embed.plnkr.co/UyA0fjX5eponD7XQI8Yj/preview

Upvotes: 1

Designing the Code
Designing the Code

Reputation: 246

Instead of writing

currentPageIndex++;

You could write a function which does this and updates the currentPage and call that instead

$scope.setPageIndex = function(index){
currentPageIndex = index;
$scope.currentPage = pages[index];
};

$scope.nextPage = function() {
$scope.setPageIndex(currentPageIndex++);
}

Or optionally if the pages and currentPageIndex variables are on scope then you could directly bind to that in your ng-include.

<div ng-include="pages[currentPageIndex]" ></div>

Upvotes: 0

thesamet
thesamet

Reputation: 6582

You can watch an arbitrary function:

$scope.$watch(function() { return currentPageIndex; }, function(newValue) {
  $scope.currentPage = pages[newValue];
});

But this watcher may not run until Angular runs its next digest cycle. So the next thing you should figure out is what changes currentPageIndex. If the code that changes currentPageIndex runs outside Angular (for example in response to a DOM event), you can wrap it in $scope.$apply():

$scope.$apply(function() { currentPageIndex = newValue; });

Upvotes: 0

Related Questions