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

AngularJS Custom Directive Access attributes in Template while inheriting parent scope

本文关键字:访问 属性 作用域 指令 自定义 继承 AngularJS      更新时间:2023-09-26

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

控制器

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,因为我继承了父作用域。是否可以从模板直接访问指令属性?

您可以继承作用域,但也可以使用以下命令创建子作用域:

scope: true

然后为了传递值:

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

这样,在指令的内部作用域中,您可以具有不同的值,同时仍然可以访问父作用域。

你可以在这里看到所有的行动:http://jsfiddle.net/HB7LU/15120/

只要不在指令中声明隔离作用域,就可以访问父作用域:

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

代码中只有一些语法错误使您无法执行此操作。在您的模板中,您不需要对传递到角度指令(ng-click和ng-show)中的值进行插值:

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

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

$scope.colname = 'col1';

否。继承父作用域时,不能访问指令属性。要做到这一点,你必须创建指令自己的作用域,如下所示:

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

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

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

我还为你制作了一把小提琴。如果你觉得这个有用,请接受这个答案。

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

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

模板

HTML标记可能:

替换指令元素的内容(默认值)。更换指令的元素本身(如果replace为true-已弃用)。包裹指令元素的内容(如果transclude为true)。价值可能be:

一根绳子。例如CCD_ 1。一个函数,它接受两个参数tElement和tAttrs(如中所述下面的编译函数api),并返回一个字符串值。

参见模板中使用属性的示例

请参阅Angular Doc 上的文档