Search code examples
angularjsangularjs-scopeangularjs-controllerangularjs-model

Referencing the element that is calling a controller function Angularjs ( ng-change / ng-blur / ng-* ? )


The original question asked about how to determine which element called the controllers blurr function, but I didn't clarify that I was not specifically asking about ng-blur, but ng-* (ng-change, ng-focus, ng-mouseover, ng-*) in general. So, with that in mind:

How do I determine which element input is calling the blurr() and/or check() functions?

html

<body ng-app="test">
  <div ng-controller="Cntrlr as cntrlr">
    <form name="meta_test">
      <input type="text" name='inpt' ng-model="cntrlr.inpt" ng-blur="cntrlr.blurr()" ng-change="cntrlr.check()" />
      <input type="text" name='second' ng-model="cntrlr.second" ng-blur="cntrlr.blurr()" ng-change="cntrlr.check()" />
    </form>
  </div>
</body>

js

var app = angular.module("test", []);
app.controller("Cntrlr", ["$scope", function($scope){
  this.blurr = function(){
    alert("which input am I?");
    alert("this is so meta.");
    // ?
  };
  this.check = function(){
    alert("this is how meta I am:");
    alert(this); 

  }
 $scope.Cntrlr = this;  // see: (reference)
 return $scope.Cntrlr; 
}]);

You may be asking yourself "why would he want to do this?"
There are 2 reasons:

  1. because I want to call:

    $scope.user_form[meta_test.[(whatever this element is.name)]].$setValidity('spike', false);

  2. because I'm curious. There has to be a simple way to do this.

(reference): controller as syntax


Solution

  • Use this -

    <input type="text" name='inpt' ng-model="cntrlr.inpt" ng-blur="cntrlr.blurr($event)" ng-change="cntrlr.check()" />
    

    This returns the jQuery lite version of the event that causes the blurr function. Once you receive this element in your controller, you can pretty much do whatever you want with it.

    The .target attribute of the event will give you the required element.

    Should work