【问题标题】:Transforming angular directive template when using isolated scope使用隔离范围时转换角度指令模板
【发布时间】:2013-08-29 09:58:41
【问题描述】:

我正在编写一个自定义指令来生成一个下拉元素。如果我使用隔离范围,编译函数不会转换模板。

大多数情况下,我正在更改 select 元素上的 ng-options,因为它们在指令中提供。我如何在隔离范围内实现相同的目标?

myApp.directive('helloWorld', function () {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      id:'@',
      label:'@'
    },
    template: '<div class="control-group">' +
                '   <label for="{{id}}" class="control-label">{{label}}</label>' +
                '   <div class="controls">' +
                '       <select id="{{id}}" class="medium m-wrap">' +
                '       </select>' +
                '   </div>' +
                '</div>',
  },
  compile:function(tElement, tAttrs, transclude){
   var opts = tAttrs.textField 
    ?'item.' + tAttrs.textField + (tAttrs.groupBy ? ' group by item.' + tAttrs.groupBy : '') + ' for item in ' + tAttrs.itemSource
    :'item for item in ' + tAttrs.itemSource;

    tElement.find('select').attr('ng-options',opts);
  }
});

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    问题是{{label}} 不存在于隔离范围内。您可以通过将对父范围的引用传递给指令中的隔离范围来解决此问题:

       return {
           restrict: 'E',
           replace: true,
           scope: {
               id:'@',
               label:'@'
           },
           // in the directive!
           controller : function($scope){
               $scope.label = $scope.$parent.label;
           }
    

    但是,这不是一个可取的范例。因为这意味着您的指令可以侦听的唯一数据是“命名”。所以最好使用一个属性,(这看起来像你正在做的)。所以...

     // in the directive!
     controller : function($scope, $attrs){
        $scope.$parent.$watch($attrs.itemSource, function(itemSource){
            $scope.itemSource = itemSource;
        });
     }
    

    类似的东西。

    【讨论】:

    • 我按照您在控制器中的建议添加了,但仍然无法正常工作
    • 不,是指令!
    • 你是在复制粘贴我的代码吗?还是看概念和学习?因为我无法深入了解您的实现,所以我将了解需要绑定到隔离范围的所有内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多