2013-04-30 102 views
0

在我當前的代碼中,我使用虛擬方式來獲取數據。它就像如何通過Ajax填充範圍變量進入控制器?

var controlMeetings = $.ajax({ 
     type: "GET", 
     url: "./Info.xml", 
     contentType: "text/xml", 
     dataType: "xml", 
     success: function (dataSource) {   

      controlMeetings = PureJson(dataSource);   
     } 
}); 

function MeetingsCtrl($scope, $compile) { 

    $scope.meetings = controlMeetings; 
    $('#div1').html(
     $compile(
     '<ul><li ng-repeat="meeting in meetings"><a>{{meeting.count}}</a> <ul><li ng-repeat="child in meeting.children">{{child.meet}}</li></ul></li></ul>' 
     )($scope) 
    ); 
    $('#div1').prepend('<div class="mHeader">Race cources</div>'); 


} 

它顯然不好(是我從這個代碼感到羞恥),但它的工作atm。問題是如何在控制器中實際填充$ cope.meetings變量並避免使用全局變量?

+0

我想你可以用角方式接地做,請按照教程 - http://egghead.io – Neil 2013-04-30 08:23:21

回答

1

我試着用AngularJS方法重寫你的例子。

控制器:

function MeetingsCtrl ($scope) { 

    $http.get('./Info.xml').success(function (data) { 
     $scope.meetings = data; 
    }); 

} 

查看文件:

<div id="div1"> 
    <div class="mHeader">Race cources</div> 
    <ul> 
    <li ng-repeat="meeting in meetings"> 
     <a>{{meeting.count}}</a> 
     <ul><li ng-repeat="child in meeting.children">{{child.meet}}</li></ul> 
    </li> 
    </ul> 
</div> 
+0

我「錯誤:$ HTTP沒有定義」 和i之後加入功能MeetingsCtrl($範圍,$編譯,$ HTTP){ $ http.get( './ Info.xml')成功(功能(數據){。 $ scope.meetings = data; });然後我開始在jquery 1.9.1中長時間運行腳本異常 – 2013-04-30 12:58:43

+0

我忘了注入'$ http',我的壞!雖然不需要'$ compile'!如果您使用jQuery的'.html()'將HTML添加到網頁,那麼您做得不對,請使用單獨的部分視圖文件!我不確定你的'Info.xml'文件是怎麼樣的(我用靜態數據來展示它的工作原理),但看到這個:http://jsfiddle.net/m23kX/ – 2013-04-30 20:00:57

+0

但我的想法是重用控制器在其他頁面和每次手動注入html。我應該每次直接輸入html嗎? – 2013-05-07 06:14:01