V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
leighton
V2EX  ›  Angular

求教 Angularjs component 封装 inputbox

  •  
  •   leighton · 2019-03-06 12:04:16 +08:00 · 4603 次点击
    这是一个创建于 1849 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我想用 component 封装一个 inputbox 文本输入框,还是需要用 ng-model 去绑定变量,然而绑定变量得到的值需加上某些前缀。比如在输入框内输入 "abcd" , 对应的 model 变量会被处理为 ” textPrefixabcd"

    Component 我是这样写的:

    angular.module('').component('dummyBox', {
        bindings: {
            ngModel: '='
        },
        require: {
            ngModelCtrl: 'ngModel'
        },
        template: '<span><input type="text" ng-model="$ctrl.ngModel" /></span>',
        controller: function() {
            $ctrl.$onInit = () => {
                $ctrl.ngModelCtrl.$parsers.push((viewValue) => {
                    if(viewValue) return "testPrefix" + viewValue;
                });
    
                $ctrl.ngModelCtrl.$formatters.push((modelValue) => {
                    return modelValue.substr("textPrefix".length);
                });
            }
        }
    });
    

    然后在外部使用时这样:

    <dummy-box ng-model="outScopeVar"></dummy-box>
    <label>{{outScopeVar}}</label>
    

    为什么不对呢,label 打印出来的永远是实际输入的值。是 ngModel 绑定错了,还是我对$formatters 和 $parsers 的理解不对?求前端大佬们指点

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5927 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 02:37 · PVG 10:37 · LAX 19:37 · JFK 22:37
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.