AngularJs指令监视异步数据

前端之家收集整理的这篇文章主要介绍了AngularJs指令监视异步数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用带有一些ajax数据的prettyprint.问题是,当调用指令时,数据没有准备好,所以我得到未定义的变量输出.

普兰克: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))
    }
};
});

解决方法

使用范围的 $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;
 })

普拉克:http://plnkr.co/edit/Autg0V

猜你在找的Angularjs相关文章