angular / angular.js

AngularJS - HTML enhanced for web apps!
https://angularjs.org
MIT License
58.81k stars 27.49k forks source link

Is directive config name + controller:"@" supported? #7615

Closed stevebroshar closed 10 years ago

stevebroshar commented 10 years ago

I've seen examples of defining a directive like this:

directive('d', function(){
  return {
    name: 'ctrl',
    controller: '@'
    ...
  }
})

With associated HTML:

<d ctrl="fubar"/>

The directive is created with controller fubar. This feature is described very well here: http://stackoverflow.com/questions/15273404/name-in-angular-directive-definition

But, I cannot find this feature described in any angularjs docs. Specifically, I looked in http://docs.angularjs.org/guide/directive and in the more detailed http://docs.angularjs.org/api/ng/service/$compile.

So, this seems to be an undocumented feature. As such, I am reluctant to use. Is this feature supported? Should I be OK to use and rely on it?

caitp commented 10 years ago

@stevebroshar this is pretty much here because ngController needs it, but it's not really intended to be public.

It's probably not going to disappear, but if it does, you know why =)

Just as a note, if you want to instantiate a custom controller with an arbitrary name based on an attribute value WITHOUT the '@' mechanic, you can inject the $controller service and do this:

if (attrs.someFancyAttribute) {
  var requestedController = $controller(attrs.someFancyAttribute, {
    $scope: someScope,
    $attrs: someMockAttributesObject, // (you could give it your real Attributes object if you wanted...)
    $element: someJQLiteElement // (you could give it your directive $element if it's appropriate)
  });

  // Make sure it stays alive for the lifetime of the jqLite element by attaching it to data
  someJQLiteElement.data('$directiveNameController', requestedController);
}

The trouble with this is that you can only get this to work at linktime, and controllers instantiated by the compiler are linked at compile-time, so it's slightly different. But it's not too bad, and you could get around it by having an intermediary compiler

caitp commented 10 years ago

Eh, I think that answered your question, so I'm gonna close this --- but if you have additional questions, don't hesitate to ask on the irc channel (http://webchat.freenode.net/?channels=angularjs), stackoverflow, or even on twitter or linkedin, why not.