Reputation:
I'm new to Angular, so the documentation is a bit of a bear. When I created the following code, and it worked, I thought I was in a good place.
<div ng-controller="postListController">
{{someDataStuff}} <!-- this always works -->
<div ng-repeat="post in data">
<b>{{post.title}}</b> <!-- This sometimes works -->
</div>
</div>
...and this Javascript in Angular (a snippet, really)
var listController = app.controller('postListController', function postListController($scope) {
$scope.someDataStuff = 'hey there.';
$scope.data = new Object(null);
$.get('get.php',function(data) {
$scope.data = JSON.parse(data);
console.log($scope.data);
});
});
someDataStuff
printed out, and Angular looped happily through the post.titles
. Then I tried moving this stuff, verbatim, to a template file and loading it appropriately...
app.directive('ngPostList', function() {
return{
restrict: 'E',
templateUrl: 'postlist.html'
}
});
This part... only sorta worked. While I was still getting data (returned it in console.log), and I was still getting someDataStuff
to come back, it was no actually looping through the data.
Is there something in app.directive I'm missing to make it pass data on to the template I'm now using?
Upvotes: 2
Views: 94
Reputation: 20798
Your template should also take the controller, otherwise it is outside the scope and you are one level further down and you would have to call $parent.post.title etc... to reach the proper parent scope with the data.
try:
app.directive('ngPostList', function() { return{ restrict: 'E', Controller: 'postListController', templateUrl: 'postlist.html' } });
Overall, pick up one of the Chrome extensions to debug Angular, like ng-inspector, so you can see what scope has what data and it makes your life a lot easier to debug this kind of things. Angular issues are 95% of the time issues with scope not being what your think it is.
Upvotes: 1