Search code examples
javascriptangularjsangularjs-directiveangularjs-scope

AngularJS textbox value undefined


I have created a directive wherein it copies the value of textbox1 to textbox2.

function myCopyText() {
    return {
        restrict: 'A',
        link: function(scope, element, attr) {
            $('#textbox2').val($('#textbox1').val())
        }
    }
}

Then on the textbox field:

<input type="text" id="textbox1" ng-model="vm.textbox1" my-copy-text />
<input type="text" id="textbox2" ng-model="vm.textbox2" />

It works fine until I submitted the form wherein vm.textbox2 is always undefined. But if I manually inputted a value on textbox2, vm.textbox2 is able to display the value.

I find it weird that when the directive do the value assignment, vm.textbox2's value is always undefined not until I manually set a value by typing it in.


Solution

  • That's by design. The angular digest kicks in when you change the value via the input/change event therefore val() will not trigger the setViewValue, so the model value will not be updated.

    This directive will replicate the value from the model/view to the name you pass in the replicate-to attribute:

    function replicateTo($parse) {
       return {
            scope: false,
            require: 'ngModel',
            restrict: 'A',
            link: function(scope, element, attr, ngModelCtrl) {
                 var target = $parse(attr.replicateTo);
    
                 var angularRender = ngModelCtrl.$render;
    
                 ngModelCtrl.$render = function(){
                    angularRender();
                    target.assign(scope, ngModelCtrl.$viewValue);
                 };
    
                 ngModelCtrl.$viewChangeListeners.push(function(){
                    target.assign(scope, ngModelCtrl.$viewValue);
                 });
            }
        }
    }
    
    <input type='text' ng-model="vm.textbox1" data-replicate-to="vm.textbox2"/> <br>