2013-07-01 33 views
0

我有一個plunkr用下面的代碼更新NG網與外部數據

HTML

<!DOCTYPE html> 
<html ng-app="myApp"> 
    <head lang="en"> 
     <meta charset="utf-8"> 
     <title>Custom Plunker</title> 
     <link rel="stylesheet" type="text/css" href="http://angular-ui.github.com/ng-grid/css/ng-grid.css" /> 
     <link rel="stylesheet" type="text/css" href="style.css" /> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> 
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script> 
     <script type="text/javascript" src="http://angular-ui.github.com/ng-grid/lib/ng-grid.debug.js"></script> 
     <script type="text/javascript" src="main.js"></script> 
    </head> 
    <body ng-controller="MyCtrl"> 
     <div id="myGrid" class="gridStyle" ng-grid="gridOptions"></div> 
     <button onclick="hi()" type="button">hi</button> 
    </body> 
</html> 

JS

var app = angular.module('myApp', ['ngGrid']); 
app.controller('MyCtrl', function($scope) { 
    $scope.gridOptions = { 
     data: 'myData', 
     showFilter: true, 
     columnDefs: [{ field: "name", width: 120 , displayName : "Name" }, 
        { field: "age", width: 120 }, 
        { field: "birthday", width: 120 }, 
        { field: "salary", width: 120 }] 
    }; 
    $scope.myData = []; 
}); 


function hi() 
{ 
scope = angular.element($("#myGrid")).scope(); 
console.log($("#myGrid") , angular.element($("#myGrid")) , scope); 
if(scope) 
scope.$apply(function(){ 
     scope.myData = [{ name: "Moroni", age: 50, birthday: "Oct 28, 1970", salary: "60,000" }, 
        { name: "Tiancum", age: 43, birthday: "Feb 12, 1985", salary: "70,000" }]; 
    }) 
} 

現在,當我點擊按鈕嗨,我希望可以通過調用apply()和設置myData來將表格的內容設置爲我想要放置的內容。然而,它不工作..我做錯了什麼?理由:基本上,我有一個複雜的邏輯(比內置緩存功能更復雜)來檢查localStorage,然後在需要時通過REST調用檢索新數據。除此之外,它是三個REST調用的結果需要進行組合。因此,對於我來說,檢索正確的範圍,分配數據和應用()跳過大量循環之後似乎是最簡單的。

回答

1

編輯基於評論

如果你想獲得正確的範圍,你只需將ID移動到控制器的元素。

<body ng-controller="MyCtrl" id="myGrid"> 

將得到正確的範圍。只有在此變更

一部開拓創新ANSWER

這似乎從你的plunkr,你實際上並沒有得到正確的範圍後,您plunkr工作。

我用更爲標準的方式在網格中獲取數據,並將其分配給plunkr。我添加了一個ng-click處理程序,以便它可以獲取控制器的範圍。

<button ng-click="hi()" type="button">hi</button> 

然後hi功能添加到控制器

$scope.hi = function(){ 
     $scope.myData = [{ name: "Moroni", age: 50, birthday: "Oct 28, 1970", salary: "60,000" }, 
         { name: "Tiancum", age: 43, birthday: "Feb 12, 1985", salary: "70,000" }]; 
    }; 

只要有你的功能控制器的範圍的一部分。然後用一個按鈕調用該函數,以便將數據放入網格中。

您可以輕鬆地從遠程源

+0

我的問題取代這個數據靜態數據真的是我怎樣才能得到正確的範圍:\ – tomdemuyt

+0

我會盡力制定到的響應。您無法在控制器內部工作的任何具體原因?這是試圖拯救你自己的設計模式 –

+0

更新的問題 – tomdemuyt