1

My controller contains an array. Each item in the array is a directive with template. How do I get value to directive when I push a new one? I want to send ID to directive when I push new item.

Controller

(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"});
}


}

})();

Directive

(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";
      }
    }
 };
})();

How does the directive get the ID when it is created?

1
  • What does the HTML look like? Because that's where you bind that id to the directive scope. Commented Feb 2, 2015 at 16:55

1 Answer 1

2

If you are looping through a collection for which you generate directives, you just have to push a new element into the collection, AngularJS will pick up the changes and handle the view.

So for instance - if this is your 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>

You see that a persondirective is created for each person in the collection. If you push a person into the people collection, a new directive will show for that person:

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

I've created a fiddle for you to demonstrate how this works: http://jsfiddle.net/k7qsxo5e/

Also - you probably want to use the '=' binding. This is a two way binding. That means that if the person being displayed in the directive is changed from the controller, the list will update. Also, if the directive changes the person, the collection in the controller will update.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, and thanks for the fiddle. I see I still have a bit to learn.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.