Angular:访问控制器构造函数中的指令属性

时间:2015-12-28 04:00:37

标签: angularjs angularjs-directive attributes angularjs-scope

(使用Angular 1.5)

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

________n_____626_______________
           |
        d  |  6
     mask  |  0001000000
   digits  |  0000000000
           |
________n_____62________________
           |
        d  |  2
     mask  |  0000000100
   digits  |  0001000000
           |
________n_____6_________________
           |
        d  |  6
     mask  |  0001000000
   digits  |  0001000100
                 ^
               bit was already set, return false

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

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

在控制台中,对于<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 } 在控制器构造函数中未定义?这种设计模式是否存在缺陷/误导?谢谢!

1 个答案:

答案 0 :(得分: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