2

I am using angular v1.3.15. My controller displays a big table from an array of objects:

$scope.table = [
  { name: "A",
    availableConnection: [
      { id: 1, displayName: "Foo" },
      { id: 2, displayName: "Bar" },
      ...
    ]},
  { name: "B",
        availableConnection: [
          { id: 1, displayName: "Doo" },
          { id: 2, displayName: "Boo" },
          ...
        ]},
  ...
];

I was wondering if it is better that my controller will hold controller for each cell in the array $scope.table.

<tr ng-repeat="x in table" ng-controller="RowController">
      <td>
          <select ng-options="a.displayName for a in availableConnection" >                          
          </select>
      </td>
</tr>

I cant copy my code because it's inside private network. This example explains what i meant. * Also the whole page got an controller so it means the hole table is inside controller.

2 Answers 2

2

Controllers in AngularJS are usually not used for any "heavy lifting", including big data sets. If you have a large data set, you should store your values in a JSON file. You can use the $http service to retrieve the data:

 $http.get("my_data.json")
    .then(function(response) {
        $scope.table = response.data;
    });

You can then use only one controller for many JSON files, and then print it on your HTML file. Hope this helps!

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

2 Comments

I am not storing the data in the controller. i get it from api. the question was if i need to make controller for every row in the table or just one for the whole page
You should use one controller for the whole table. If you use a controller for every row, then you have no need for ng-repeat, which in the end will stop you from repeating yourself in your code. I hope my answer is clear! :)
1

Whether to use nested controllers or not is judgement call, but this tutorial states that scope should refer to the model, not be the model -- so don't model/put your data into scopes. Your models/data should normally be in a service.

When developing an Angular application, at first try to think about your models. Put them in services or factory with APIs to get/edit/manipulate the models. Then next step is to design your views. Each view should project/use/manipulate some subset of your models. Create a controller for each view that simply glues the needed subset of the models to the view. Make your controllers as thin as possible.

So, in my view, it is better not to use nested controllers as you should know how to properly use nested controllers. Your code gets more complicated, if you use nested controllers.

Comments

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.