Brian
Brian

Reputation: 3568

Angular: accessing directive attributes in controller constructor

(Using Angular 1.5)

I am trying to use the following design pattern for my angular app:

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

I use my directive in my HTML like this:

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

In the console, for self I see:

Object { otherAttr: undefined, someId: undefined }

and for $attrs I see:

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

How may I accomplish what I am trying to accomplish (i.e. passing data from parent scope into my directive controller constructor), and why is even my single binding ("@" binding) otherAttr undefined in the controller constructor? Is this design pattern is flawed/misguided? Thanks!

Upvotes: 1

Views: 2234

Answers (1)

diegochavez
diegochavez

Reputation: 662

looks like you have the naming conventions wrong on the directive, you should define the name on directive attribute as "data-content" and use on the controller as "dataContent"

Take a look this demo i've done

// 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

Upvotes: 2

Related Questions