2014-12-03 242 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