I want to add a new function to the ng-blur of all input/textarea fields. The input fields and textarea's has a existing ng-blur in the html and I want to add a new function to the existing ng-blur within the controller.
I tried to add it with setAttribute, but that override the existing ng-blur functions.
const formElems= iElem[0].querySelectorAll('input, textarea');
formElems[0].setAttribute('data-ng-blur', 'newFunction()');
$compile(angular.element(formElems[0]))($scope);
I want to extend the functions inside ng-blur, but not directly in the HTML.
How to add new functions inside the controller to the ng-blur of all input and textarea's and keep the current functions?
You don't need to do anything in your template.
Just create a new function in your controller and call this function from already exists function. It will not break your existing functionality.
See example below -
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>
Finally, I found a solution by getting the existing attribute first by using getAttribute().
const oldAttributes = formElems[0].getAttribute('ng-blur');
formElems[0].setAttribute('ng-blur', oldAttributes + ' testConsole();');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.