Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

(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!

share|improve this question
up vote 1 down vote accepted

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

share|improve this answer
    
Wow--that was it, thanks! That part wasn't really clear to me from the docs--I thought the camelcase conversion was just something angular would do if you used hyphens in your attribute/directive names. – Brian Dec 28 '15 at 5:42

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.