2

How do you pass an object to a directive? I'm trying to access users in my directive's scope without success. This is what I've tried:

In my controller I set an array of users to a scope:

$scope.users = payload.data.results;

Then I want to pass that object to my directive as an attribute:

<display test123='users'></display>

The directive function:

function ListDisplay() {
    var directive = {
      replace: 'true',
      restrict: 'E',
      scope: {
        test123: '='
      },
      controller: ListDisplayController,
      controllerAs: 'vm',
      bindToController: true,
      link: ListDisplayLinkFunc
    };

    return directive;


    function ListDisplayController($scope) {
      console.log($scope.test123);

    }

    function ListDisplayLinkFunc(scope, elem, attr) {

      console.log(scope.test123);
    }
  }

But when I try to console out scope.data I get undefined.

7
  • 1
    I think data is related to html5 attribute.try to use some other name.It might help Commented Feb 1, 2016 at 12:36
  • thanks @RIYAJKHAN I've changed it to test123 and still get undefined. :( Commented Feb 1, 2016 at 12:40
  • Can we have sample plunker? Commented Feb 1, 2016 at 12:41
  • Is payload in payload.data.results is a promise? Commented Feb 1, 2016 at 12:43
  • Please share our dir def Commented Feb 1, 2016 at 12:43

2 Answers 2

2

you are using controllerAs: 'vm' and bindToController: true, this means that the values you pass in the scope are assigned to a variable called vm

Try this:

function ListDisplayController($scope) {
  var vm = this;
  console.log(vm.test123);

}

to handle using "bindToController" in the link function you can do

function ListDisplayLinkFunc(scope, elem, attr) {

  console.log(scope.vm.test123);
}

you can see it in this plunker: http://plnkr.co/edit/r2wuTE5oafYeu8h3Cjio?p=preview

Sign up to request clarification or add additional context in comments.

Comments

2

Seems like payload.data.results is a result of an AJAX call. Your directive is being compiled before your AJAX call is succeeded. So you need to register a watch in your controller to get the value when the data is updated via the AJAX call.

function ListDisplayLinkFunc(scope, elem, attr) {
    console.log(scope.test123);

    scope.$watch('test123', function(newValue) {
         if (newValue) {
            console.log('Updated users in the directive', newValue);
         }
    });
}

2 Comments

It looks like the answer as a combination of both @valepu and Shashank Agrawal answers, what to do????
Well both were the issue, first the data had not finished being loaded and then controllerAs assigned it to a variable called vm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.