0

This is my scenario,

view:

<div data-ng-controller="MyModuleController">
   <div ng-repeat="a in range() track by $index" >
      <ty-project idx="$index+1" ng-model="projects[$index]" ></ty-project>
   </div>
</div>

controller:

$scope.projects= [];

$scope.range = function() {
    // return some random number - it does not really matter for the purpose
};

ty-project is just a directive

angular.module('mymodule').directive('tyProject', [
     function() {
         return {
            templateUrl: 'modules/mymodule/directives/typrojectTemplate.html',
             restrict: 'E',
             scope: {
                   idx: '='
             },
             link: function postLink(scope, element, attrs) {
             }
       };
    }
]); 

typrojectTemplate is a simple template with 2 inputs,as following:

  <div>
      <label>Project_{{idx}} name</label>
      <input type="text" name="project.name" ng-model="project.name"/>
  </div>
  <div >
     <label >Project_{{idx}} total </label>
     <input type="number" name="project.total" ng-model="project.total" />
 </div>

this is my controller

angular.module('mymodule').controller('MyModuleController', ['$scope', 
    function($scope) {

       $scope.projects: [] ;

        $scope.save = function() {

            console.log(projects);
        };

        $scope.range = function() {
            var n= 2;// todo: return random number..
            return new Array(n);
        };
    }
]);

so in case range method return 2 there will be 2 projects object each project has name and total attributes.

how can I bind the projects to the controller?

Thanks.

john Smith
  • 1,565
  • 7
  • 34
  • 54

1 Answers1

1

hay you have to pass the scope from the controller to the directive. The directive will pass this scope to the template.

you could do this in your directive:

scope:{
       project: '=ngModel'//will pass it to the Template.
       idx: '=' //
}

i dont know, whether u assigned the controller to the view.

AngularLover
  • 364
  • 1
  • 12