1

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

1 Answer 1

2

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

1
  • 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, 2015 at 5:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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