如何在指令中获取属性参数

How to get an attribute parameter in a directive

本文关键字:获取 属性 参数 指令      更新时间:2023-09-26

我有以下代码。我正在尝试将myController范围内的name作为nameAttr属性注入 myObj 指令。

我已经在指令的作用域上分配了name: '=nameAttr',但它似乎不起作用。

我做错了什么?

https://plnkr.co/edit/qceVMl0w2gv03ZuQVQb8?p=preview

.HTML

<my-obj nameAttr="name"></my-obj>

在"我的-OBJ"内部。目录'

<h2>{{ name }}</h2>
<ol>
  <li ng-repeat="(slug, val) in loop">{{ slug }} - {{ val }}</li>
</ol>

var mod = angular.module('myApp', []);
mod.controller('myController', myController).directive('myObj', myObject);
function myController($scope){
  $scope.name = 'John Smith';
}
function myObject(){
  return {
    restrict: 'E',
    templateUrl: 'my-obj.html',
    scope: {
      name: '=nameAttr'
    },
    controller: function($scope){
      $scope.loop = {
        'one': 'gfshfh',
        'two': '32435'
      };
    }
  };
}

在你的index.html中你需要写

<my-obj name-attr="name"></my-obj>

------------------^

具有camelCase名称的Directives必须按照模板中的camel-case

Angular 规范化元素的标记和属性名称,以确定哪些元素与哪些指令匹配。我们通常通过区分大小写的驼峰规范化名称(例如 ngModel)来引用指令。但是,由于HTML不区分大小写,因此我们通过小写形式引用DOM中的指令,通常在DOM元素上使用破折号分隔的属性(例如ng-model)。

规范化过程如下:

Strip x- and data- from the front of the element/attributes.
Convert the :, -, or _-delimited name to camelCase.

指令文档在这里