2013-08-29 37 views
0

我正在編寫自定義指令以生成下拉元素。如果我使用隔離範圍,則編譯函數不會轉換模板。使用隔離範圍時轉換角度指令模板

大多數情況下,我正在改變select元素上的ng選項,因爲它們是在指令中提供的。我將如何實現與隔離範圍相同的目標?

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

回答

0

問題是{{label}}不存在於隔離範圍內。你可以通過傳遞一個參考家長範圍隔離範圍的指令內解決這個問題:

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

然而,這不是一個明智的範例。因爲這意味着你的指令可以聽的唯一數據是'named'。所以最好使用一個屬性,(看起來像你正在做的)。所以...

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

東西沿着這些線。

+0

我按照你在控制器中的建議添加了,但它仍然不會工作 – Syam

+0

不,它是指令! – Fresheyeball

+0

是的,在指令控制器中。 – Syam