Encountering a problem with AngularJS ng-view
and ng-repeat
, specifically related to managing the scope
. Using ng-repeat
to display a list of items from an array, with a button outside the ng-repeat
scope
triggering an array update on ng-click
. However, unable to get this functionality to work correctly. Below is a snippet of the code:
<!-- home.html partial -->
<h1>Home view</h1>
<div>
<ul ng-repeat="p in posts.data">
<li>{{p.title}}</li>
</ul>
<a href="#" ng-click="updatePosts(5)">More</a>
</div>
Controller bound to this partial file:
var app = angular.module('plunker', ['ngRoute']);
app.config(function($routeProvider){
$routeProvider
.when('/', {
controller: 'testController',
templateUrl: 'home.html'
})
.otherwise({ redirectTo: '/' });
});
app.controller('testController',
[
'$scope',
function ($scope)
{
$scope.posts = {
data : []
};
$scope.getPosts = function(count)
{
for(i =0; i<count; ++i)
{
$scope.posts.data.push({title : "Title-"+i})
}
}
$scope.updatePosts = function(count)
{
var offset = $scope.posts.data.length;
var data = [];
for(i =offset; i<offset+count; ++i)
{
data.push({title : "Title-"+i});
}
$scope.posts.data = $scope.posts.data.concat(data)
}
$scope.getPosts(5);
}
]
);
Desired functionality is for the controller to fetch snippets of data upon clicking "More" and update the view accordingly. For example, transitioning from (1) to (2) when clicking "More". However, always stuck at (1) without progress.
(1)
Home View
- Title-0
- Title-1
- Title-2
- Title-3
- Title-4
More
(2)
Home View
- Title-0
- Title-1
- Title-2
- Title-3
- Title-4
- Title-5
- Title-6
- Title-7
- Title-8
- Title-9
More
Code example also available on Plnkr here
** update**
Tried the same code without ng-view
and it functioned as expected. Issue seems to stem from usage of ng-view
. Example setup without ng-view
on Plnkr here