And*_*loi 16 javascript angularjs
我尽力将这个问题作为精确的标题.
我对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
}
});
Run Code Online (Sandbox Code Playgroud)
我index.html拿起app.js并有一个引用的锚#/lineup,它有效地打开views/lineup.html; 为了简化,我们假设后者只包含(自定义)<playerlist></playerlist>标签.
在指令的控制器功能中,我确信它$.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>
Run Code Online (Sandbox Code Playgroud)
我的想法是让"playerlist"指令独立LineupCtrl于我可能想在项目的其他地方重用它.
好的,所以这里是:当我点击#/lineup第一次加载的锚点时,tbody上面表格的元素是空的(没有附加任何行); 有趣的是,当我第二次点击它时,表格会正确填充我收到$.get("/players")指令的玩家.我怀疑这是由于playerlist.html的呈现和分配的$ scope.players变量之间出现的轻微延迟.但这不是一个角度应用的全部意义吗?当范围变量更改时,相应的视图(及其模板)会更新吗?
请帮忙!
干杯,
安德里亚
Yos*_*shi 40
每当您更新角度函数之外的范围变量时,您需要告知角度更改的内容.见scope.$apply.
$.get("/players")
.success(function(players) {
$scope.$apply(function () {
$scope.players = players;
});
});
Run Code Online (Sandbox Code Playgroud)
另外,angular有一个内置的ajax服务,因此不需要使用jQuery.可以在教程中找到一个很好的解释:5 - XHR和依赖注入.
| 归档时间: |
|
| 查看次数: |
14493 次 |
| 最近记录: |