2014-12-03 236 views
2

我有一個要求,當單擊一個元素(Button)時應該改變另一個元素屬性。 我可以通過jquery來完成。但我想忽略我的角度項目中的jQuery。通過angularjs中的另一個元素獲取元素

在HTML中,

<input type=password /> 
<button ngclick="changeToTxt()">Change type password to text</button> 

在控制器,

app.controller('loginPage', function ($scope) { 
    $scope.changeToTxt = function() { 
    **// need to get the password element and need to change type = text.....** 
    } 
}); 

有沒有一種方法(或不同的/最好的方法)由控制器做什麼?或者需要爲此寫一條指令?

回答

2

U可以很容易地改變類型動態

這裏是工作代碼fiddle

<div ng-app="app"> 
    <div ng-controller="MainController"> 
    <input type={{test}} /> 
    <input type="button" value="change" ng-click="changeType()"/> 
    </div> 
</div> 


angular.module('app', []). 
    controller('MainController', ['$scope', function ($scope) { 
    $scope.test = "text"; 

    $scope.changeType = function() { 
     $scope.test = "password"; 

    }; 
}]); 
+0

這是跨瀏覽器兼容嗎?我認爲它不適用於IE。你有沒有在不同的瀏覽器上試過它? – user1537766 2014-12-03 06:51:25

+1

是的。我已在所有平臺上進行過測試。它將一切工作。 – simon 2014-12-03 06:54:06

+0

適用於IE9及以上版本,不在下面http://www.universalwebservices.net/web-programming-resources/javascript/change-input-element-type-using-javascript – 2014-12-03 07:03:17

2

您不能動態更改輸入類型。

你有沒有考慮過使用兩個按鈕,一個是密碼類型和其他類型的文本。你可以使用ng-hide屬性在點擊按鈕時隱藏其中的一個(這是一個黑客攻擊)。

+0

好的。但我想過傳遞元素並獲取控制器範圍內的元素(如jquery或javascript直接方法)。 – Hello 2014-12-03 06:40:46

5

你可以保持兩個輸入要做到這一點

,你可以嘗試這樣的事情

<input type="password" ng-model="pwd" ng-show="!showText" /> 
<input type="text" ng-model="pwd" ng-show="showText" /> 

<button ng-click="showText = !showText ">Change type password to text</button> 

這裏工作plunker

+0

這種情況的好方法。 – Hello 2014-12-03 11:08:00