1) giải pháp đầu tiên lấy cảm hứng từ this question và nó là Module
's value
method:
<script>
var users_json = '[{"name":"Piotr"},{"name":"Natasha"}]'; // created by xsl
myApp.value("PrimaryData" , users_json);
</script>
<ul>
<li ng-repeat="user in users">{{user.name}}</li>
</ul>
Sau đó, chúng ta có thể sử dụng này PrimaryData
khi nào và nơi chúng ta muốn, như thế này:
myApp.controller('MainCtrl', function($scope, PrimaryData) {
$scope.data = angular.copy(PrimaryData);
console.log($scope.data[0].name === "John");
});
Nhưng cách này bằng cách nào đó không làm việc cho tôi khi tôi bắt đầu sử dụng routes
, có thể là do value
chỉ chạy trong khi khởi tạo ứng dụng.
2) Vì vậy, ở đây có giải pháp thứ hai: chỉ thị. Bây giờ khi máy chủ gửi mẫu của một tuyến đường, nó đặt bên trong một số script
thẻ với một loại "text/template"
và đặc biệt sở hữu tên chỉ thị và dữ liệu json trong thẻ đó, như thế này:
<script type = "text/template" rawdata > <!-- "rawdata" is our directive
'[{"name":"Nelson"},{"name":"Luis"}]' // created by xsl
</script>
<ul>
<li ng-repeat="user in users">{{user.name}}</li> // view is beside
</ul>
Và chỉ thị này bắt nó và chuyển dữ liệu với phạm vi tuyến đường hiện tại ':
studio.directive('rawdata', function() {
return {
link: function(scope, element, attr, ctrl) {
if(scope.passRawData){
var data = (element[0].innerHTML);
scope.passRawData(data); // Or simply scope.users = JSON.parse(data)
} else {
console.log("Scope has no passRawData method");
}
}
}
});
Tuyệt vời! :)
bản sao có thể có của [tải dữ liệu ban đầu trong angularjs] (http://stackoverflow.com/questions/18086823/initial-data-loading-in-angularjs) –