使用双向绑定动态地将对象从角度视图添加到数组到控制器

san*_*ore 9 javascript angularjs angularjs-directive angularjs-scope

我有一个控制器,控制器的模板/视图如下,

myController的

angular.module('myApp', []).
controller('myController', ['$scope', function($scope) {
        $scope.myObject = {};
}]);
Run Code Online (Sandbox Code Playgroud)

我的看法

<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>
Run Code Online (Sandbox Code Playgroud)

这里,每当用户进入它被反射到的任何数据myObjectfirstnamelastname用于动态属性myObject.现在,我的新要求是添加多个动态视图用于firstnamelastname在同一视图(对于我将创建一个指令,并动态地追加),现在我想myObject成为一个array of objects

myObjectArray = [{firsname: "abc", lastname: "xyz"},{firsname: "abc", lastname: "xyz"},{firsname: "abc", lastname: "xyz"},{firsname: "abc", lastname: "xyz"}]
Run Code Online (Sandbox Code Playgroud)

这里应该通过使用角度双向绑定的用户输入动态添加视图来填充每个对象.但我不知道如何通过angular实现这一点,如果有动态查看添加新指令模板,如何将对象添加到数组中.

Abh*_*jar 21

在Angular中,你应该避免考虑动态控制.

这是方法

  1. 您想列出firstname,lastname对象
  2. 您想要将新对象添加到此列表中.

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: ''
    })
  }
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

请注意,这些只是谈论模型.这是一个插件