2013-02-20 62 views
16

我試圖給這個問題提供一個精確的標題。
我是AngularJS的新手,但我在這個問題上跺腳。我試圖讓jsfiddle更好地說明我的問題,但它依賴於太多的單獨文件。唉,它還沒有在線,所以請留神。 :)

所以基本上我有一個應用程序我yeoman init angular建成,我app.js看起來是這樣的:如果範圍通過ajax填充,AngularJS指令模板不會更新

"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,從而有效地打開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> 

我的想法是讓「playerlist」指令獨立LineupCtrl,因爲我可能要在項目中的其他地方重複使用。
好的,在這裏:當我點擊第一次加載#/lineup的錨時,上表中的tbody元素爲空(沒有行追加到它);有趣的是,當我再次點擊它時,表格正確地填充了我通過$.get("/players")指令得到的玩家。我懷疑這是由於在playerlist.html的渲染和$ scope.players變量被分配之間發生的輕微滯後。但是,這不是一個角度應用程序的整個點?當範圍變量更改相應視圖(及其模板)時會更新?
請幫忙!
乾杯,

安德烈

+0

優秀的問題!謝謝。 – I159 2013-05-05 15:02:39

回答

39

每次更新的角度函數外範圍的變量,你需要告訴角的東西改變了。見scope.$apply

$.get("/players") 
.success(function(players) { 
    $scope.$apply(function() { 
    $scope.players = players; 
    }); 
}); 

在不同的音符,角度有一個內置的ajax service,所以沒有必要使用jQuery。一個很好的解釋可以在教程中找到:5 - XHRs & Dependency Injection

+0

感謝您快速準確的回覆!那正是我需要的!如果可以的話,我會加倍努力,但不幸的是我缺乏聲譽...... :( 關於你的一面說明:我將研究angular內置的ajax服務的使用,我使用了jQuery,因爲底層模型層依賴於本地運行的節點服務器,它從本地mysql數據庫獲取數據 – 2013-02-21 08:48:31

+0

我可以通過簡單地調用'$ .get(「/ players」)'來抽象它,因爲在另一個文件(即'lib.js')中,我有$ .ajaxPrefilter(function(options){ options.url =「http:// localhost:3000」+ options.url; options.crossDomain = true; options.async = false; return「jsonp」; });' (跨域是必需的,因爲我的應用在localhost:3501中運行,yeoman的默認服務器和節點在localhost:3000上運行)。 o直到我找到一種方法來實現純角度的同一事物(我發現學習曲線非常陡峭)。 – 2013-02-21 08:49:09

+0

P.S.現在如果我發出'$ http。get(「/ players」)'它會查找'http:// localhost:3501/players',這個不存在。 再次感謝!乾杯! – 2013-02-21 08:49:29