【问题标题】:How to add new functions to ng-blur in the controller?如何在控制器中为 ng-blur 添加新功能?
【发布时间】:2020-07-20 16:55:52
【问题描述】:

我想向所有输入/文本区域字段的 ng-blur 添加一个新功能。 输入字段和 textarea 在 html 中有一个现有的 ng-blur,我想在控制器内的现有 ng-blur 中添加一个新功能。

我尝试使用 setAttribute 添加它,但它会覆盖现有的 ng-blur 函数。

const formElems= iElem[0].querySelectorAll('input, textarea');
formElems[0].setAttribute('data-ng-blur', 'newFunction()');
$compile(angular.element(formElems[0]))($scope);

我想在 ng-blur 中扩展功能,但不是直接在 HTML 中。

如何将控制器内的新功能添加到所有输入和文本区域的 ng-blur 并保留当前功能?

【问题讨论】:

    标签: javascript angularjs angular


    【解决方案1】:

    您无需在模板中执行任何操作。

    只需在您的控制器中创建一个新函数并从已存在的函数中调用此函数。它不会破坏您现有的功能。

    参见下面的示例 -

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
      $scope.firstName= "John";
      $scope.lastName= "Doe";
      
      $scope.myFunction = function(){
        console.log('Your current working code');
        $scope.extendedFunction();
      }
      
      $scope.extendedFunction = function(){
        console.log('You should write your new code here');
      }
      
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
    <div ng-app="myApp" ng-controller="myCtrl">
    
    First Name: <input type="text" ng-model="firstName" ng-blur="myFunction();"><br>
    Last Name: <input type="text" ng-model="lastName" ng-blur="myFunction();"><br>
    <br>
    Full Name: {{firstName + " " + lastName}}
    
    </div>

    【讨论】:

    • 我也是这么想的,但是有些输入字段没有功能或者不是同一个功能。是否没有在控制器中扩展而不在存在函数中扩展的替代方法?
    • 我没有其他选择。但是你可以做一件事,对于那些目前没有任何模糊事件的输入,你可以添加extendedDunction作为一个事件。对于那些有其他功能的,在函数的最后,你可以调用extendedDunction,就像我们从myFunction调用一样。
    • 好的,感谢@Alok Mali 的评论。我会寻找解决方案,也许有人有解决方案:)
    【解决方案2】:

    最后,我找到了一个解决方案,首先使用 getAttribute() 获取现有属性。

    const oldAttributes = formElems[0].getAttribute('ng-blur');
    formElems[0].setAttribute('ng-blur', oldAttributes + ' testConsole();');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-07
      • 1970-01-01
      • 2016-04-11
      • 2013-05-24
      • 1970-01-01
      相关资源
      最近更新 更多