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

限于喜欢 提交于 2019-12-14 03:02:43

问题


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


回答1:


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




回答2:


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.
  }
}


来源:https://stackoverflow.com/questions/24616524/referencing-the-element-that-is-calling-a-controller-function-angularjs-ng-cha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!