0

The original question問及如何確定哪個元素稱爲控制器blurr函數,但我沒有說明我是沒有具體詢問ng-blur,但通常是ng- *(ng-change,ng-focus,ng-mouseover,ng- *)。因此,考慮到這一點:引用正在調用控制器函數的元素Angularjs(ng-change/ng-blur/ng- *?)

如何確定哪個元素輸入調用了 blurr()和/或 check()函數?

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; 
}]); 

你可能會問自己: 「他爲什麼要這麼做?」
有2個原因:

  1. ,因爲我想打電話:

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

  2. ,因爲我很好奇。必須有一個簡單的方法來做到這一點。

(參考): controller as syntax

回答

1

使用此 -

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

這將返回導致羅嗦函數的事件的jQuery的精簡版的版本。一旦你在你的控制器中接收到這個元素,你幾乎可以隨心所欲地做任何事情。

該事件的.target屬性將爲您提供所需的元素。

應工作

0

試試這個:

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

在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. 
    } 
} 
+0

(總是使用全等) –

相關問題