allencoded
allencoded

Reputation: 7265

Scope Isolation & nested directives

Dealing with '&' and isolated scope.

Is it possible to pass a value up through a parent directive? I want to pass id from the textdisp directive to the controller.

HTML:

<body ng-controller="MainCtrl">
    <builder removequest="deleteQuestion(id)"></builder>
  </body>

ANGULAR:

app.controller('MainCtrl', function($scope) {
  $scope.deleteQuestion = function(id) {
    alert(id);
  }
});

app.directive('builder', function() {
  return {
    restrict: 'E',
    scope: {
      removequest: '&'
    },
    template: '<div>Hello how are you? <textdisp removequest=removequest(id)></textdisp></div>'
  }
});


app.directive('textdisp', function() {
  return {
    restrict: 'E',
    scope: {
      removequest: '&'
    },
    template: '<div ng-click="remove()">Click here!</div>',
    link: function (scope, el) {
      scope.remove = function(id) {
        console.log('workin')
        scope.removequest(1);
      }
    }
  }
 });

Upvotes: 1

Views: 78

Answers (2)

dfsq
dfsq

Reputation: 193251

It's a little confusing, but you can use object parameter when you need to pass values into your function invoked via & binding. Take a look at this code it will make everything clear:

app.controller('MainCtrl', function($scope) {
    $scope.deleteQuestion = function(id) {
        alert(id);
    }
});

app.directive('builder', function() {
    return {
        restrict: 'E',
        scope: {
            removequest: '&'
        },
        template: '<div>Hello how are you? <textdisp removequest="removequest({id: id})"></textdisp></div>'
    }
});


app.directive('textdisp', function() {
    return {
        restrict: 'E',
        scope: {
            removequest: '&'
        },
        template: '<div ng-click="remove()">Click here!</div>',
        link: function(scope, el) {
            scope.remove = function(id) {
                scope.removequest({id: 34534}); // <-- 1.
            }
        }
    }
});

Demo: http://plnkr.co/edit/3OEy39UQlS4EyOu5cq4y?p=preview

Note how you specify scope.removequest({id: 34534}) parameter to be passed into <textdisp removequest="removequest({id: id})">.

Upvotes: 1

Morgan Delaney
Morgan Delaney

Reputation: 2439

I believe there are 2 things going on with your code:

  1. When you're placing removequest="removequest(id)" that is calling the function, and not just referring to the function.
  2. I believe that the &attr binding isn't returning the function that you're expecting.

Try this Plunker; it essentially uses { removequest: '=' } for bi-directional binding, and removequest="deleteQuestion" / removequest="removequest" for function references rather than calling the function.

Upvotes: 1

Related Questions