使用数组推送将变量传递给指令

Passing variable to directives, with array push

我的控制器包含一个数组。数组中的每一项都是带有模板的指令。当我推送一个新指令时,我如何获得指令的价值?我想在推送新项目时将 ID 发送到指令。

控制器

(function () {
  'use strict';

angular
  .module('app')
  .controller('dashboardController', dashboardController);

dashboardController.$inject = ['$scope', '$timeout', '$state', 'apiService'];

function dashboardController($scope, $timeout, $state, apiService) {

$scope.newCMP = newCMP;
$scope.openCMPArray = [];

function newCMP() {
  $scope.openCMPArray.push({id:"3"});
}


}

})();

指令

(function () {
  'use strict';

  angular
      .module('app')
      .directive('gpCmpForm', cmpForm);

  function cmpForm() {
    return {
      scope: {
        id: '=id' //I've tried doing a lot of different mapping here
      },
       restrict: 'A',
      templateUrl: '/app/views/cmpForm.html',
      controller: function ($scope) {
        $scope.test = "342";
      }
    }
 };
})();

指令创建时如何获取ID?

如果您循环遍历为其生成指令的集合,则只需将新元素推送到集合中,AngularJS 将获取更改并处理视图。

例如 - 如果这是你的 HTML:

<div ng-controller="mycontroller">
    <a href="#" ng-click="addPerson()">click to add person</a>
    <div ng-repeat="person in people">
        <div persondirective person="person"></div>
    </div>
</div>

您看到为集合中的每个人创建了一个 persondirective。如果您将一个人推入人员集合,将为该人显示一个新指令:

$scope.addPerson = function() {
    $scope.people.push({ name: 'new guy' });
};

我创建了一个 fiddle 来演示它是如何工作的:http://jsfiddle.net/k7qsxo5e/

此外 - 您可能想要使用“=”绑定。这是双向绑定。这意味着如果指令中显示的人从控制器更改,则列表将更新。另外,如果指令更改了人,控制器中的集合将更新。