我尽量给这个问题起一个准确的标题。
我是 AngularJS 的新手,但我被这个问题困扰了。我试图制作一个 jsfiddle 来更好地说明我的问题,但它依赖于太多单独的文件。唉,它还没有上线,所以请忍受冗长。 :)
所以基本上我有一个用 yeoman init angular
构建的应用程序,还有我的 app.js
看起来像这样:
"use strict"
var myApp = angular.module("myApp", [])
.config(function($routeProvider) {
$routeProvider
.when("/lineup", {
templateUrl: "views/lineup.html",
controller: "LineupCtrl"
})
//other routes
.otherwise({
redirectTo: "/"
});
})
.directive("playerlist", function() {
return {
restrict: "E",
transclude: false,
scope : {},
templateUrl : "views/directives/playerlist.html",
controller : function($scope) {
$.get("/players")
.success(function(players) {
$scope.players = players;
});
},
replace : true
}
});
我的 index.html
拿起app.js
并且有一个引用 #/lineup
的 anchor , 这有效地打开了 views/lineup.html
;为了简化事情,我们假设后者只包含(自定义)<playerlist></playerlist>
标签。
在指令的 Controller 函数中,我确定 $.get("/players")
可以正常工作,因为我可以从 chrome 的网络选项卡中看到响应作为一组播放器正确通过。
最后,我的 views/directives/playerlist.html
具有替换 <playerlist>
的代码标记,如下所示:
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Role</th>
<th>Strength</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="player in players">
<td>{{player.first_name}} {{player.last_name}}</td>
<td>{{player.age}}</td>
<td>{{player.role}}</td>
<td>{{player.strength}}</td>
</tr>
</tbody>
</table>
我的想法是让“playerlist”指令独立于LineupCtrl
因为我可能想在项目的其他地方重用它。
好的,开始吧:当我点击加载 #/lineup
的 anchor 时第一次,tbody
上表的元素为空(没有附加行);有趣的是,当我第二次点击它时,表格中正确填充了我用 $.get("/players")
得到的球员。操作说明。我怀疑这是由于 playerlist.html 的呈现和分配的 $scope.players 变量之间发生的轻微滞后。但这不是 Angular 应用程序的全部意义所在吗?当作用域变量发生变化时,相应的 View (及其模板)会更新吗?
请帮忙!
干杯,
安德里亚
最佳答案
每当您在 Angular 函数之外更新作用域变量时,您需要告诉 Angular 发生了某些变化。参见 scope.$apply
.
$.get("/players")
.success(function(players) {
$scope.$apply(function () {
$scope.players = players;
});
});
换句话说,angular 有一个内置的 ajax service ,所以不需要使用 jQuery。可以在教程中找到很好的解释:5 - XHRs & Dependency Injection .
关于javascript - 如果范围是通过 ajax 填充的,则 AngularJS 指令模板不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14984777/