2

I want to encapsulate a inputBox into AngularJS component. This component will automatically add some prefix to the input before it's passed to binding model data. For example the prefix is "testPrefix", when user input "ABC", the corresponding model data will be "testPrefixABC".

My code is like this:

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>

For now it's not working, the content in label is still the input value, no prefix string added. Any help will be appreciated.

Thanks in advance.

1
  • I found the answer after reading this question. I mixed ngModel in my template with ngModel in bindings. Commented Mar 6, 2019 at 7:25

1 Answer 1

0

the above code works with directive instead of component,

app.directive("inputEncaps", function(){
        return {
            require: "ngModel",
            link: function(scope, element, attrs, ngModel){
                ngModel.$parsers.push((viewValue) => {
                    if(viewValue && !viewValue.includes("textPrefix")) {
                        return "testPrefix" + viewValue;
                    } else {
                        return viewValue;
                    }
                });
    
                ngModel.$formatters.push((modelValue) => {
                    let model = modelValue && modelValue.length >= "textPrefix".length ? 
                    modelValue.substr("textPrefix".length) : modelValue;
                    return modelValue;
                });
            }
        };
    });
<input ng-model="inputVar" input-encaps/>

<label>{{inputVar}}</label>

Sign up to request clarification or add additional context in comments.

1 Comment

I figured out how to use ngModels in my component, but still thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.