如何通过transclude将父指令属性值传递给子指令范围?

时间:2016-04-28 19:14:06

标签: javascript angularjs angularjs-directive angularjs-scope angular-template

我试图通过ng-transclude将指令中的属性值传递给子指令的范围。我尝试过使用=,@,&对于范围绑定,我仍然感到困惑。我希望child指令继承父指令中的属性。任何帮助将不胜感激!

我在这里制作了一个jsfiddle - > https://jsfiddle.net/egdfLzLj/5/

的Javascript

var app = angular.module('app', []);

app.directive('parent', function () {
    return {
    restrict: 'E',
    transclude: true,
    replace: true,
    scope: {
        label: '@'
    },
    template: '<section>' +
            '<label>{{::label}}' + 
            '<ng-transclude></ng-transclude>' +
            '</label>' +
      '</section>'
  };
});

app.directive('child', function () {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      type: '@',
      label: '&'
    },
    template: '<input ng-type="type" ng-value="::label">'
  };
});

HTML

<parent label="Parent Label">
  <child type="text"></child>
</parent>

1 个答案:

答案 0 :(得分:1)

演示:https://jsfiddle.net/egdfLzLj/2/

HTML

<parent label="Parent Label">
    <child type="text"></child>
</parent>

指令

var app = angular.module('app', []);

app.directive('parent', function () {
    return {
    restrict: 'E',
    transclude: true,
    replace: true,
    scope: {
        label: '@'
    },
    template: '<section>' +
            '<label>{{::label}}' + 
            '<ng-transclude></ng-transclude>' +
            '</label>' +
      '</section>'
  };
})

app.directive('child', function () {
  return {
    restrict: 'E',
    replace: true,
    link: function (scope) {scope.label =  scope.$parent.label;},
    template: '<input type="text" value="{{ label }}">'
  };
});