mercredi 30 mars 2016

Is an application-level controller acceptable in Angular when used for constants?

I am creating an application that has a lot of interacting sub-components. Many of the different views display some of the same data in summary format. The data that is retrieved from the REST calls returns codes, and I need to do lookups for those codes. I want to create an application-level controller to hold all the code-translate objects (constants) used everywhere. Would this follow best practices?

Something along the lines of below. So the main body will have the "appCtrl" that houses the constants built off web-services, and then the different includes can reference them as children of the parent controller.

index.html

 <body>
        <div data-ng-controller="appCtrl" class="container-fluid">    
            <div data-ng-include data-src="'navigation/navigation.html'"></div>
            <div id="mainContent" data-ng-view></div>
            <div id="versionTag">
                APP: v<span data-app-version></span>
            </div>
        </div>
</body>

navigation.html

<div data-ng-controller="aumNavigationCtrl">
.
.
.
</div>

app.js (this is truncated to give you an idea)

    .controller('appCtrl', ['$scope','Tasks',
      function($scope, Tasks)
      {
        //define task types to use in app
        $scope.taskTypes = [];
        Tasks.getTypes({},{}).$promise.then(
          function(data)
          {
            for (var i = 0; i < data.length; i++)
            {
              $scope.taskTypes[i] = 
              { 
                 "code": data[i].code, 
                 "description": data[i].description
              };
            }
          });
    });

navigation.js (again, truncated for brevity)

.controller('aumNavigationCtrl', ['$scope',
function($scope)
{
    $scope.getTypeDescrip = function(typeCode)
    {
      for (var i = 0; i < $scope.taskTypes.length; i++)
      {
        if (typeCode === $scope.taskTypes[i].code)
        {
          $scope.typeDescrip = $scope.taskTypes[i].description;
        }
      }
    }
});

Aucun commentaire:

Enregistrer un commentaire