【问题标题】:Angular programmatically add ngChange without attributeAngular以编程方式添加没有属性的ngChange
【发布时间】:2014-04-18 07:49:34
【问题描述】:

我正在尝试在不修改 HTML 的情况下模拟指令中的 ng-change 属性(因此没有 ng-change 属性)。

查看 ngChange 指令的 Angular 源代码,我的指令有效,看起来像这样: (基本上在这个指令中,当modelchange时我需要blur()一个select字段)

.directive('blurOnChangeFix', ['$timeout',
    function($timeout) {
        return {
            restrict: 'AEC',
            require: 'ngModel',
            link: function($scope, element, attr, ngModel) {
                    // automatically blur element on ngModel change
                    ngModel.$viewChangeListeners.push(function() {
                    $timeout(function() { // IE bug fix
                        $(element).blur();
                    }, 100);
                });
            }
        };
    }
]);

应用它:

<select
    id="test"
    ng-options="option for option in ['test1', 'test2'] track by option"
    class="form-control"
    ng-model="form.test"
    ng-required="true"
    blur-on-change-fix
></select>

但这是正确的解决方案吗?没有其他方法可以做到这一点吗? scope.change() 呢?

谢谢

【问题讨论】:

    标签: javascript angularjs angularjs-directive angular-ngmodel angularjs-ng-change


    【解决方案1】:

    如果我理解正确,您正在寻找在您的模型上使用$watch;例如:

    link: function($scope, element, attr, ngModel) {
        $scope.$watch(attr.ngModel,function(newVal,oldVal) {
            element.blur();
        })
    

    model发生变化时,你说你想做点什么,所以这是$watch的用法。

    【讨论】:

    • 感谢您的解释,我遗漏了一些东西 ;)
    • 是的,我想我误会了 ngChange 的使用。我将编辑我的答案。 $watch$ 在这里仍然是正确的用法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    • 2014-06-11
    • 2014-08-27
    • 2021-06-06
    • 1970-01-01
    相关资源
    最近更新 更多