ngUpgraders / ng-forward

The default solution for those that want to write Angular 2.x style code in Angular 1.x
411 stars 36 forks source link

Add ng-id directive to mimic the #id feature #113

Open timkindberg opened 8 years ago

timkindberg commented 8 years ago

I had an idea to add a directive called ng-id that would work just like #name does in Angular 2. It would be an easy migration of find/replace. It would work as follows:

<input ng-id="userName">

userName would be added to the scope.

Unknowns: I'm not sure if this is a variable that's limited to the template html only or if it can be accessed by component controllers. I'm pretty sure its template only, so let's start there.

timkindberg commented 8 years ago

Once we have ng-id, we could add a template helper that supports converting #name into ng-id="name", so we could support the real syntax as well. This is similar to how we currently convert ng-content to ng-transclude before registering the component as a directive.

timkindberg commented 8 years ago

Would need to have a pretty high priority so that all other directives could reference the element in their expressions. The current highest priorities are ngSwitch at 1200. I'm thinking going to 1500 would be good. There's no good reason to not set this very high as it's pretty innocuous.

MikeRyanDev commented 8 years ago

If it is template only, then I imagine this would actually be a pretty straightforward addition. Would make for a great community contribution!

Steps to implement:

  1. Create an attribute directive that injects $scope, $element, and $attrs. You could do this in the directive's controller, or in the link function
  2. Use $attrs to read the name of the ID
  3. Use $element to get the tagName of the element (this will be the element's name, i.e. <my-component/>'s name would be myComponent
  4. Use $element.controller(tagName) to get the instance of the component's controller
  5. Set the variable on the scope: $scope[ID] = controllerInstance

If anyone wants to take a stab at this, let me know and I'll gladly help!

timkindberg commented 8 years ago

Also, If the controller instance is not found you'd have to assign the $scope.id to be the element reference.