【问题标题】:Angular 1.5 Components + ng-model $formatters and $parsersAngular 1.5 组件 + ng-model $formatters 和 $parsers
【发布时间】:2017-07-28 10:56:14
【问题描述】:

我想知道如何将 $formatters 和 $parsers 与 angular 1.5 组件一起使用。谁能发个例子。

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

【问题讨论】:

  • 使用 ng-form directive 将 API 绑定到范围。 (不要将ng-model 与组件隔离范围绑定。)然后阅读AngularJS Developer Guide - Implementing Custom Form Controls Using ng-model
  • 我很乐意看到这个问题得到一个很好的答案。 @georgeawg 为什么不“将 ng-model 与组件隔离范围绑定”?
  • 这个问题长期以来没有得到解答的原因可能是因为组件的绑定/返回模型的单一方式让这个问题变得没有意义。如果您要避免双向绑定(这始终是一个好主意),您可以在用户弄乱值时转换您的模型 => 视图 $onInit 和视图 => 模型(通过调用更新 ('&') 函数并使用 ng-change 或其他一些用户触发的操作传递新值。
  • 我也很想看到这个问题的答案。
  • 我很快就会发布一个例子。我们一直在我们的应用程序中使用双向绑定。

标签: angularjs angular-ngmodel angular-components


【解决方案1】:

以下是名为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>

【讨论】:

    猜你喜欢
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    • 2015-07-05
    • 2015-11-24
    • 2014-10-15
    • 2017-01-20
    相关资源
    最近更新 更多