Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs directive watching async data

Tags:

angularjs

I'm trying to use prettyprint with some ajax data. The problem is that when the directive is invoked, the data arem't ready, so I get undefined variable output.

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))
    }
};
});
like image 393
Tropicalista Avatar asked Sep 23 '13 06:09

Tropicalista


1 Answers

Use scope's $watch method:

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

And instead of this:

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

Use this:

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

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

like image 70
Ivan Chernykh Avatar answered Oct 11 '22 22:10

Ivan Chernykh