Referencing the element that's calling a controller function Angularjs

蓝咒 提交于 2019-12-06 15:59:08

问题


Fairly simple but I can't figure out the term I need to google. How do I reference whichever element is calling the controllers blurr function?

html

<body ng-app="test">
  <div ng-controller="Cntrlr as cntrlr">
    <input type="text" ng-model="cntrlr.inpt" ng-blur="cntrlr.blurr()" />
    <input type="text" ng-model="cntrlr.second" ng-blur="cntrlr.blurr()" />
  </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.");
    // ?
  };
}]);

[edit]

I realized I meant to be more abstract than I was so I created a new question because this one has been solved


回答1:


You could pass the $event to the function, and figure out the target of the event from that:

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

And

$scope.blurr = function(event){
    var $this = $(event.target);
    console.log($this);
};


来源:https://stackoverflow.com/questions/24615597/referencing-the-element-thats-calling-a-controller-function-angularjs

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