shreyansh
shreyansh

Reputation: 1687

AngularJS Directive data binding not happening from controller

I am facing the problem of data binding from controller to directive because of delay in response from the server.

To better understand just see a small program below.When I remove the timeout function, binding happens.

<msg track="{{customer}}"></msg>



angular.module('myApp').directive('msg',  function() {

  return {
      scope: {
        track :"@"
      },
      link : function(scope, element, attrs) {

      },
      template : "<a href>{{track}}</a>"
  }

});

angular.module('myApp').controller('HomeCtrl', ['$scope', function($scope) {
    setTimeout(function() {
      $scope.customer = "shreyansh";
    }, 5000);
    // assume some service call inside controller 
    // service1.getData().then(function(data){$scope.customer = data})
}]);

How can i fix above problem so that above code should render as

<msg track="shreyansh" class="ng-isolate-scope"><a href="" class="ng-binding">shreyansh</a></msg>.

Any help is appreciated.

Thanks

Upvotes: 0

Views: 45

Answers (1)

Sumit Deshpande
Sumit Deshpande

Reputation: 2155

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

app.factory('myService', function($http) {
  var promise;
  var myService = {
    getData: function() {
      if (!promise) {
        promise = $http.get('test.json').then(function(response) {
          return response.data;
        });
      }
      return promise;
    }
  };
  return myService;
});

app.controller('MainCtrl', function(myService, $scope) {
  myService.getData().then(function(d) {
    $scope.data = d;
  });
});

app.directive('msg', function() {
  return {
    restrict: 'E',
    scope: {
      track: "@"
    },
    link: function(scope, element, attrs) {
    },
    template: "<a href>{{track}}</a>"
  }
});



 <msg track="{{data.name}}"></msg>

test.json file

{
  "name": "Pete"
}

Upvotes: 1

Related Questions