2013-09-23 33 views
5

Tôi đang cố gắng sử dụng dấu vân tay với một số dữ liệu ajax. Vấn đề là khi chỉ thị được gọi, dữ liệu không sẵn sàng, vì vậy tôi nhận được đầu ra biến không xác định.Chỉ thị AngularJ xem dữ liệu không đồng bộ

Plunkr: http://plnkr.co/edit/fdRi2nIvVzT3Rcy2YIlK?p=preview

var app = angular.module('plunker', []); 

app.controller('MainCtrl', function($scope,$http) { 


$scope.result = $http.get('data.json').success(function(result){ 
    return result.data.dom 
}) 

}); 


app.directive('prettyprint', function() { 
return { 
    restrict: 'C', 
    link: function postLink(scope, element, attrs) { 
      element.html(prettyPrintOne(scope.result)) 
    } 
}; 
}); 

Trả lời

5

Sử dụng scope 's $watch phương pháp:

scope.$watch("result" , function(n,o){ 
     element.html(prettyPrintOne(scope.result)); 
}) 

Và thay vì điều này:

$scope.result = $http.get('data.json').success(function(result){ 
     return result.data.dom 
}) 

Sử dụng này:

$http.get('data.json').success(function(result){ 
     $scope.result = result.dom; 
}) 

Plunk: http://plnkr.co/edit/Autg0V

+0

Tôi đã cập nhật plunkr, nhưng điều này dường như không hoạt động ... – Tropicalista

+0

@Tropicalista tôi thấy. Tôi đã cập nhật câu trả lời của mình, hãy xem – Cherniv

Các vấn đề liên quan