范围隔离&嵌套指令

时间:2014-05-21 19:20:40

标签: angularjs angularjs-scope

处理'&'和孤立的范围。

是否可以通过父指令传递值?我想将id从textdisp指令传递给控制器​​。

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);
      }
    }
  }
 });

2 个答案:

答案 0 :(得分:1)

我相信您的代码会发生两件事:

  1. 当您放置调用该函数的removequest="removequest(id)"时,而不只是引用该函数。
  2. 我认为&attr绑定没有返回您期望的功能。
  3. Try this Plunker;它本质上使用{ removequest: '=' }进行双向绑定,使用removequest="deleteQuestion" / removequest="removequest"进行函数引用,而不是调用函数。

答案 1 :(得分:1)

这有点令人困惑,但是当您需要将值传递到通过&绑定调用的函数时,可以使用object参数。看看这段代码,它将使一切清晰:

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.
            }
        }
    }
});

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

请注意您如何指定要传递到scope.removequest({id: 34534})的{​​{1}}参数。