N.Car
N.Car

Reputation: 492

AngularJS - Insert info dinamically into controller according to a ng-repeat from another controller

I created a very simple example in order to make it easier to understand.

Here I have ng-repeat that calls a template. This template has its own controller. However, the controller of the template needs to be injected some data from the service in each ng-repeat. In this demonstration it has to be the answer to the question. How can I achieve that?

  <div ng-repeat="fighter in fighters">
    <div ng-if="fighter.state">
      {{fighter.question}}
      <div ng-include="'template.html'" ng-controller="Controller2"></div>
    </div>
    <br>
    <br>
  </div>

If you want to see the whole demo working, check this plunker:

DEMO PLUNKER

Upvotes: 0

Views: 26

Answers (1)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41447

In your template.html create a ng-init function and pass the obj

<div ng-controller="Controller2" ng-init="getAnwser(fighter)">
  <div>
    <!-- Inserir pergunta que vem da base de dados aqui-->
    <input type="text" ng-model="answer"  />
  </div>
  <div>
    <button ng-click="checkAnswer()">
      ANSWER
    </button>
    <div ng-show="showAnswer">Correct</div>
  </div>

</div>

in controller2 implement the function

$scope.getAnwser = function(obj){
  console.log(obj.answer)
}

Demo

Upvotes: 1

Related Questions