Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

unique form element names in directive template code #6268

Closed
@lookfirst

Description

@lookfirst

I have a need for unique names (and form validation) in my directive template. I'm starting to see a fairly ugly non-DRY pattern starting to emerge in my directives. It looks something like this (apologies for coffeescript, it's what I prefer):

    module = angular.module('foo', [])
    module.directive 'blah', ->
        restrict: 'E'
        replace: true
        scope: {}
        template: ->
            """
                <div ng-form="myForm">
                    <input type="text" dynamic-name="0" />
                    <input type="text" dynamic-name="1" />
                </div>
            """
    module.directive 'dynamicName', ->
        require: '^blah'
        controller: ($scope, $element, $attrs) ->
            unix = new Date().getTime()
            ELEMENT_NAMES = ["one#{unix}", "two#{unix}"]
            $attrs.$set('name', ELEMENT_NAMES[parseInt($attrs.dynamicName)])

I got the idea from @caitp 's excellent suggestion in issue #1404 . By doing it this way, it somehow causes things to register correctly with the formcontroller (I'm still relatively new to angular so all the pieces don't fit together well yet for me).

I'm filing this as a new issue because the other PRs (#4791, #5231) seemed to apply more towards interpolating the name attribute in a regular page template or within a repeat loop. Feel free to close if you think it is a duplicate.

I really wish there was a better way.

Update: I'm now running into this issue: http://docs.angularjs.org/error/$compile:multidir because I've tried to use dynamicName directive in multiple modules, but rendering on the same page and they are conflicting with each other. Making the directive more unique fixes the issue, but is also hacky. I thought that require: would cause things to get scoped better.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions