Angular pass dynamic scope to directive

CaribouCode

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?

eladcon

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>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related