【问题标题】:Angular: accessing directive attributes in controller constructorAngular:在控制器构造函数中访问指令属性
【发布时间】:2015-12-28 13:12:24
【问题描述】:

(使用 Angular 1.5)

我正在尝试为我的 Angular 应用程序使用以下设计模式:

angular.module("app").directive("MyDirective", MyDirective);

function MyDirective () {
  return {
    bindToController: {
      someId: "=",
      otherAttr: "@"
    },
    controller: ["$attrs", MyController],
    controllerAs: "ctrl"
  };
}

function MyController ($attrs) {
  var self = this;
  console.log(self);
  console.log($attrs);
}

我在我的 HTML 中这样使用我的指令:

<my-directive someId="someParentScope.model._id" otherAttr="1">

在控制台中,self 我看到了:

Object { otherAttr: undefined, someId: undefined }

对于$attrs 我明白了:

Object { $attr: Object, $$element: Object, otherattr: "1",
  someid: "someParentScope.model._id", otherAttr: undefined, someId: undefined,
  $$observers: Object }

我怎样才能完成我想要完成的事情(即将数据从父范围传递到我的指令控制器构造函数),为什么我的单个绑定(“@”绑定)otherAttr 在控制器构造函数中未定义?这种设计模式是否有缺陷/被误导?谢谢!

【问题讨论】:

    标签: angularjs angularjs-directive attributes angularjs-scope


    【解决方案1】:

    看起来你在指令上的命名约定有误,你应该将指令属性上的名称定义为“data-content”,并在控制器上使用“dataContent”

    看看我做的这个演示

    // directive HTML    
    <my-directive some-id="name" other-attr="1"></my-directive>
    
    //app.js 
    var app = angular.module('plunker', []);
    
    app.controller('MainCtrl', function($scope) {
      $scope.name = 'World';
    });
    
    app.directive('myDirective', function() {
            return {
              restrict: 'E',
              bindToController: {
                someId: "=",
                otherAttr: "@"
              },
              controller: ["$attrs", MyController],
              controllerAs: "ctrl"
            }
          });
    
    
    function MyController ($attrs) {
      var self = this;
      console.log(self);
      console.log($attrs);
    }
    

    http://plnkr.co/edit/P3VKdO?p=preview

    【讨论】:

    • 哇——就是这样,谢谢!我从文档中并不太清楚这部分——我认为如果你在属性/指令名称中使用连字符,那么驼峰式转换只是 Angular 会做的事情。
    猜你喜欢
    • 2016-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 2017-05-25
    • 1970-01-01
    • 2010-11-03
    相关资源
    最近更新 更多