Angular 1.5 Components + ng-model $ formatters和$ parsers

时间:2017-03-08 02:13:13

标签: angularjs angular-ngmodel angular-components

我想知道如何使用带有1.5角组件的$ formatters和$ parsers。有人可以发布一个例子。

或者是否有类似我可以使用的东西。

1 个答案:

答案 0 :(得分:0)

下面是一个名为example的组件的示例。这将包含一个包含firstNamesecondName的对象。然后,它显示firstNamesecondName的组合。如果对象从外部更改,则格式化程序将触发,然后进行渲染。如果要从内部触发更改,则需要调用this.ngModel.$setViewValue(newObject),这将触发解析器。

    class example {
        /*@ngInject*/
        constructor() {}

        // In the post link we need to add our formatter, parser and render to the ngmodel.
        $postLink() {
            this.ngModel.$formatters.push(this.$formatter.bind(this));
            this.ngModel.$parsers.push(this.$parser.bind(this));
            this.ngModel.$render = this.$render.bind(this);
        }

        // The formatter is used to intercept the model value coming in to the controller
        $formatter(modelValue) {
            const user = {
                name: `${modelValue.firstName} ${modelValue.secondName}`
            };

            return user;
        }

        // The parser is used to intercept the view value before it is returned to the original source
        // In this case we want to turn it back to it's original structure what ever that may be.
        $parser(viewValue) {
            // We know from out formatter that our view value will be an object with a name field

            const namesParts = viewValue.name.split(' ');

            const normalisedUser = {
                firstName: namesParts[0],
                secondName: namesParts[1],
            };

            return normalisedUser;
        }

        // This will fire when ever the model changes. This fires after the formatter.
        $render() {
            this.displayName = this.ngModel.$viewValue.name;
        }
    }

class ExampleComponent
{
    bindings = {};
    controller = Example;
    require = {
        ngModel: 'ngModel',
    };
}

component('example', new ExampleComponent());


    // Template for example component
    <span>
        {{ $ctrl.displayName }}
    </span>

    // Using the above component somewhere    
    <example ng-model="userModel"></example>