简体   繁体   中英

Passing custom directive attribute to ng-model in template

I'm trying to pass in some attributes to my <custom-input> directive. Like so...

<custom-input type="text" name="first_name" title="First Name"></custom-input>

However, I'm getting a syntax error for the line where I pass the attribute to ng-model in the template.

I'm not sure what I'm doing wrong? Everything was working before I tried to move into a custom directive.

Directive

.directive('customInput', function() {
        return {
            restrict: 'E',
            scope: {
                type: '@type',
                name: '@name',
                title: '@title'
            },
            templateUrl: './assets/templates/custom-input.html',
            controller: function() {
                this.data = {}
                this.focus = null;
            },
            controllerAs: 'input'
        };
    })

Template

<div class="Form__field">
    <input
        ng-model="input.data.{{name}}"
        ng-class="{'Form__input--is-filled': input.data.{{name}}.length > 0}"
        ng-focus="input.focus='{{name}}'"
        ng-blur="input.focus=null"
        class="Form__input"
        type="{{type}}"
        name="{{name}}"
        placeholder="{{title}}"
    />
    <label
        ng-show="input.data.{{name}}.length > 0"
        ng-class="{'Form__label--is-active': input.focus === '{{name}}'}"
        class="Form__label"
        for="{{name}}"
    >{{title}}</label>
    <div
        class="Info Info--default"
        ng-show="input.focus === '{{name}}'">
    </div>
</div>

Error

Error: [$parse:syntax] Syntax Error: Token '{' is not a valid identifier at column 12 of the expression [input.data.{{name}}] starting at [{{name}}].

Before:

input.data.{{name}}

After:

input.data[name]

Your inner scope is getting type, name, and title attached directly to it. By defining the scope in the directive definition, you are declaring an isolate scope--one that no longer has access to the outer scope. You're also not passing in your input object.

What you have is the same as doing this inside the controller:

scope.name = 'first_name'; scope.title = 'First Name'; scope.type = 'text';

If you follow @bchemy's suggestion, you'll get a new property on your empty input.data object called first_name. And then the contents of the input would go into that. But there's no reason to expect that anything will come into it, because you didn't pass anything in that you're putting into that variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM