5

我正在尝试将 prettyprint 与一些 ajax 数据一起使用。问题是当指令被调用时,数据还没有准备好,所以我得到未定义的变量输出。

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))
    }
};
});
4

1 回答 1

5

使用方法scope$watch

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

而不是这个:

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

用这个:

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

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

于 2013-09-23T06:12:57.393 回答