我是 Angular 的新手,所以文档有点麻烦。当我创建以下代码并运行时,我认为我来对地方了。
<div ng-controller="postListController">
{{someDataStuff}} <!-- this always works -->
<div ng-repeat="post in data">
<b>{{post.title}}</b> <!-- This sometimes works -->
</div>
</div>
...以及这个 Angular 中的 Javascript(实际上是一个片段)
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
打印出来,Angular 愉快地循环遍历 post.titles
。然后我尝试将这些东西逐字移动到模板文件并适本地加载它......
app.directive('ngPostList', function() {
return{
restrict: 'E',
templateUrl: 'postlist.html'
}
});
这部分……只有一点点有效。虽然我仍在获取数据(在 console.log 中返回它),并且我仍在获取 someDataStuff
返回,但实际上并没有循环遍历数据。
我在 app.directive 中是否缺少某些东西,无法将数据传递到我现在使用的模板?
最佳答案
你的模板也应该带 Controller ,否则它在范围之外,你在下一级,你将不得不调用 $parent.post.title 等...以使用数据到达正确的父范围。
尝试:
app.directive('ngPostList', function() { 返回{ 限制:'E', Controller :'postListController', templateUrl: 'poSTList.html' } });
总的来说,选择一个 Chrome 扩展来调试 Angular,比如 ng-inspector ,所以你可以看到什么范围有什么数据,它让你的生活更容易调试这类事情。 Angular 问题在 95% 的情况下是范围与您认为的不一样。
关于javascript - Angular 代码在移动到模板文件时停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27681205/