【问题标题】:ng-model value does not get updated on ngModelCtrl.$commitViewValue();ng-model 值不会在 ngModelCtrl.$commitViewValue() 上更新;
【发布时间】:2017-12-12 07:25:45
【问题描述】:

我有一个指令,其中有一个模板,并且我正在尝试在用户单击 Enter 时更新 ng-model。我能够捕捉到事件并尝试更新值。我在控制器中的元素上有一个观察者,但在 commitViewValue 之后永远不会触发观察者函数

(function() {
    'use strict';

    angular.module('aa')
        .directive('ss', [
            function() {

                return {
                    restrict: 'EA',
                    replace: true,
                    transclude: true,
                    scope: {
                        placeholder: '@'
                    },
                    require: 'ngModel',
                    template: '<div class="clear">' +

                        '<input type="text" ng-model="ngModel" ng-model-options="{updateOn:\'change blur\'}" />' +
                        '</div>',

                link: function (scope, elem, attrs, ngModelCtrl) {
                    elem.bind("keyup",function(e) {
                        if (e.keyCode === 13) {
                            e.stopImmediatePropagation();
                            ngModelCtrl.$commitViewValue();
                            scope.$apply(ngModelCtrl.$setTouched);
                        }
                    });
                }

                }
            }
        ]);
})();


 $scope.$watch('pr', function(newValue,oldValue){
                console.log('val>>' + newValue);
            });
<ss ng-model="pr"></ss>

【问题讨论】:

    标签: javascript angularjs web frontend


    【解决方案1】:

    使用$setViewValue 将数据从隔离范围移动到父范围:

      link: function (scope, elem, attrs, ngModelCtrl) {
            elem.bind("keyup",function(e) {
                if (e.keyCode === 13) {
                    e.stopImmediatePropagation();
                     ̶n̶g̶M̶o̶d̶e̶l̶C̶t̶r̶l̶.̶$̶c̶o̶m̶m̶i̶t̶V̶i̶e̶w̶V̶a̶l̶u̶e̶(̶)̶;̶
                    //USE $setViewValue
                    ngModelCtrl.$setViewValue(scope.ngModel);
                    //scope.$apply(ngModelCtrl.$setTouched);
                }
            });
    

    如果您希望父控制器能够设置模型,也可以使用单向 &lt; 绑定。

    scope: {ngModel: '<'}
    

    DEMO on PLNKR

    有关详细信息,请参阅

    【讨论】:

    • 感谢您的回答!完美运行。
    猜你喜欢
    • 2016-12-09
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    相关资源
    最近更新 更多