CaribouCode
CaribouCode

Reputation: 14438

Angular pass dynamic scope to directive

I have a directive that takes an attribute value from a an http call like so:

Controller

app.controller("HomeController", function($scope){
  $http.get("/api/source").then(function(res){
    $scope.info = res.data
  });
});

HTML

<div ng-controller="MainController">
  <ng-mydirective data-info="{{info}}"></ng-mydirective>
</div>

Directive:

app.directive("ngMydirective", function(){
  return {
    restrict: "E",
    templateUrl: "/partials/info.html", 
    link: function(scope, element, attrs){
      scope.info = attrs.info;
    }
  }
});

I'm trying to pass that info variable from the controller, into the directive, through an attribute. It doesn't work because the variable value is initially created from an asynchronous http call, so at the time the directive is created, there is no value.

Is there a way to do this?

Upvotes: 2

Views: 2570

Answers (1)

eladcon
eladcon

Reputation: 5825

You can observe the attribute's value:

link: function(scope, element, attrs){
      attrs.$observe('info', function(val) {
        scope.info = val;
      })
}

Also, if you can change the directive scope to be isolated, you can do it by binding the values:

app.directive("ngMydirective", function(){
  return {
    restrict: "E",
    scope: {info: '='},
    templateUrl: "/partials/info.html", 
    link: function(scope, element, attrs){

    }
  }
});

<div ng-controller="MainController">
   <ng-mydirective info="info"></ng-mydirective>
</div>

Upvotes: 2

Related Questions