0
如何更改(類型)動態添加按鈕的屬性?在下面的代碼中,標籤名稱完全改變,但是當我嘗試更改按鈕類型時,它將應用於所有添加的動態按鈕,我的要求是必須更改每種按鈕類型的不同類型(表示:要提交的第一個按鈕,第二個重置,第三次取消)。但在我的代碼,如果我更改第二個按鈕類型爲'重置'在同一時間第一個按鈕類型也將重置類型...可以ü請告訴我如何更改每個添加元素的按鈕類型...?更改動態添加元素的屬性
更新時間:
var app = angular.module('myapp', ['ngSanitize']);
app.controller('ButtonCtrl', function($scope, $compile) {
var counter = 0;
$scope.buttonFields = [];
$scope.add_Button = function(index) {
$scope.buttonFields[counter] = {button: 'Submit'};
var buttonhtml = '<div ng-click="selectButton(buttonFields[\'' + counter + '\'])"><button id="button_Type">{{buttonFields[' + counter + '].button}}</button>//click//</div>';
var button = $compile(buttonhtml)($scope);
angular.element(document.getElementById('add')).append(button);
$scope.changeTosubmit = function (val) {
$scope.buttonField = val;
var els = document.body.querySelectorAll('#button_Type');
for (var i = 0, ils = els.length; i < ils; i++) {
var el = els[i];
el.setAttribute("type", "submit");
compile(el);
}
};
$scope.changeToreset = function (val) {
$scope.buttonField = val;
var els = document.body.querySelectorAll('#button_Type');
for (var i = 0, ils = els.length; i < ils; i++) {
var el = els[i];
el.setAttribute("type", "reset");
compile(el);
}
};
$scope.changeTocancel = function (val) {
$scope.buttonField = val;
var els = document.body.querySelectorAll('#button_Type');
for (var i = 0, ils = els.length; i < ils; i++) {
var el = els[i];
el.setAttribute("type", "cancel");
compile(el);
}
};
++counter;
};
$scope.selectButton = function (val) {
$scope.buttonField = val;
$scope.showButton_Types = true;
};
});
function compile(element) {
var el = angular.element(element);
$scope = el.scope();
$injector = el.injector();
$injector.invoke(function ($compile) {
$compile(el)($scope);
});
};
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>
<script src="https://code.angularjs.org/1.5.0-rc.0/angular-sanitize.min.js"></script>
</head>
<body ng-controller="ButtonCtrl">
<button ng-click="add_Button($index)">Add Buttons</button>
<hr>
\t <div id="add"></div>
\t <form ng-show="showButton_Types">
<div>
<label>Button Name(?)</label><br/>
<input ng-model="buttonField.button">
</div>
<div>
<label>change button types(?)</label><br/>
<input ng-click="changeTosubmit(buttonFields['' + counter + ''])" name="submit" type="radio"> Submit
<input ng-click="changeToreset(buttonFields['' + counter + ''])" name="submit" type="radio"> Reset
<input ng-click="changeTocancel(buttonFields['' + counter + ''])" name="submit" type="radio"> Cancel
</div>
\t </form>
</body>
</html>
你能清理一下你的代碼,因爲它真的很難閱讀。否則,我只會在調用中添加按鈕的索引,並將引用存儲在數組中,所以當您單擊選項時,您可以使用引用來根據索引更改類型。 – eesdil