[英]Enable Two Way Data Binding when adding them dynamically to the template in (using innerHtml) Angular 4 +
[英]Dynamically adding/creating object to array from angular view to controller using two way binding
我有一個控制器,控制器的模板/視圖如下,
myController的
angular.module('myApp', []).
controller('myController', ['$scope', function($scope) {
$scope.myObject = {};
}]);
我的看法
<div class="container" ng-app="myApp">
<form name="myForm" novalidate ng-controller="myController">
<div class="form-group">
<label for="firstname" class="control-label col-xs-2">Name</label>
<div class="col-xs-10">
<input type="text" ng-model="myObject.firstname" id="firstname">
</div>
</div>
<div class="form-group">
<label for="lastname" class="control-label col-xs-2">LastName</label>
<div class="col-xs-10">
<input type="text" ng-model="myObject.lastname" id="lastname">
</div>
</div>
</form>
</div>
這里,只要用戶輸入任何數據,它就會被反映到myObject
,其firstname
和lastname
作為myObject
動態屬性。 現在我的新要求是在同一個視圖中為firstname
和lastname
添加多個動態視圖(為此我將創建一個指令並動態追加),現在我希望myObject
是一個像這樣array of objects
myObjectArray = [{firsname: "abc", lastname: "xyz"},{firsname: "abc", lastname: "xyz"},{firsname: "abc", lastname: "xyz"},{firsname: "abc", lastname: "xyz"}]
這里應該通過使用角度雙向綁定的用戶輸入動態添加視圖來填充每個對象。 但我不知道如何通過angular實現這一點,如果有動態查看添加新指令模板,如何將對象添加到數組中。
在Angular中,你應該避免考慮動態控制。
這是方法
var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { $scope.items = []; $scope.itemsToAdd = [{ firstName: '', lastName: '' }]; $scope.add = function(itemToAdd) { var index = $scope.itemsToAdd.indexOf(itemToAdd); $scope.itemsToAdd.splice(index, 1); $scope.items.push(angular.copy(itemToAdd)) } $scope.addNew = function() { $scope.itemsToAdd.push({ firstName: '', lastName: '' }) } });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="plunker" ng-controller="MainCtrl"> <p>Hello {{name}}!</p> <div ng-repeat="item in items"> {{item.firstName}} {{item.lastName}} </div> <div ng-repeat="itemToAdd in itemsToAdd"> <input type="text" ng-model="itemToAdd.firstName" /> <input type="text" ng-model="itemToAdd.lastName" /> <button ng-click="add(itemToAdd)">Add</button> </div> <div> <button ng-click="addNew()">Add new</button> </div> </body>
請注意,這些只是談論模型。 這是一個插件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.