Referencing the element that is calling a controll

2019-08-31 03:07发布

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

2条回答
趁早两清
2楼-- · 2019-08-31 03:32

Try this:

<form name="meta_test">
  <input type="text" name='inpt' ng-model="cntrlr.inpt" ng-blur="cntrlr.blurr()" 
    ng-change="cntrlr.check('One')" />
  <input type="text" name='second' ng-model="cntrlr.second" 
    ng-blur="cntrlr.blurr()" ng-change="cntrlr.check('Two')" />
</form>

In JS,

this.check = function(Type){
  if(Type == "One"){
    //Then it is the first text box.
  }else if(Type == "Two"){
    //Then it is the second text box.
  }
}
查看更多
Root(大扎)
3楼-- · 2019-08-31 03:38

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

查看更多
登录 后发表回答