AngularJS自定义指令在继承父作用域时访问模板中的属性

时间:2015-02-06 21:24:13

标签: javascript angularjs angularjs-directive angularjs-scope

我有一个自定义指令,我想继承父作用域。我还想通过属性传递一个值。它看起来像这样:

控制器

app.controller('Main', ['$scope', function($scope){
   $scope.cols = { 'col1': true, 'col2':false, 'col3': true};

   $scope.toggleCol = function(colName){
       $scope.cols[colName] = !$scope.cols[colName];
   };
}]);

指令

wrApp.directive("custTh", function(){
 return {
    restrict: "EA",
    scope: false,
    replace: true,
    template: '<th ng-show="cols[{{ colname }}]" ng-click="toggleCol({{ colname }})">{{ colname }}</th>',

 };
});

HTML

<th cust-th colname="col2"></th>

我似乎无法访问属性值bc我继承父范围。是否可以直接从模板访问指令属性?

4 个答案:

答案 0 :(得分:0)

只要您不在指令中声明隔离范围,就可以访问父范围:

<-- cust-th template can access Main controller's scope -->
<div ng-controller="Main">
  <th cust-th></th>
</div>

您的代码中只有一些语法错误阻止您执行此操作。在模板中,您不需要插入传递给angular指令的值(ng-click和ng-show):

<th ng-show="cols[colname]" ng-click="toggleCol(colname)">{{ colname }}</th>   

colname尚未在控制器中声明为范围变量,因此当Angular编译HTML时,它将无法识别它。如果您希望继续将其作为HTML元素的属性传递,则需要在指令中创建一个角度元素,以便使用链接函数访问该值(请参阅https://docs.angularjs.org/guide/directive)。如果你想使用插值({{colname}}),那么你需要在你的控制器中有一个变量,如

$scope.colname = 'col1';

答案 1 :(得分:0)

没有。继承父作用域时,无法访问指令属性。要做到这一点,你必须创建指令自己的范围,如下所示:

app.directive("custTh", function(){
      return {
      restrict: "EA",
      scope: { colname: '@'},   
      template: 'Name : {{ colname }}',
    };
});

在你的HTML remplate中,你必须这样写:

<div ng-controller="Main">   
   <cust-th colname="col2" ></cust-th>
</div>

我也为你提供了帮助。我觉得这很有用,请接受这个作为答案。

http://jsfiddle.net/HB7LU/10806/

答案 2 :(得分:0)

您可以继承范围,但也可以使用以下方法创建子范围:

scope: true

然后为了传递值:

link: function(scope, element, attrs) {
     scope.$watch(attrs.valueFromOutside, function(newValue) {
         scope.valueFromOutside = newValue;
     });
 }

这种方式在指令的内部范围内,您可以拥有不同的值,同时仍然可以访问父范围。

你可以在这里看到一切: http://jsfiddle.net/HB7LU/15120/

答案 3 :(得分:0)

模板可以是字符串或函数:

  

模板

     

可能的HTML标记:

     

替换指令元素的内容(默认)。更换   指令的元素本身(如果replace为true - DEPRECATED)。换行   指令元素的内容(如果transclude为true)。价值可能   是:

     

一个字符串。例如<div red-on-hover>{{delete_str}}</div>。   一个带有两个参数tElement和tAttrs的函数(在中描述)   下面的编译函数api)并返回一个字符串值。

请参阅use attribute in template

上的示例

请参阅Angular Doc

上的文件
相关问题