1

I am working on a CMS that I originally was using Knockout but I decided to try Angular because it like more of its functionality. In the CMS, one of the sections will be 'Users'. It has a table that allows the headers to be clicked to sort the data. The controller is below:

userControllers.controller('UserListControl', ['$scope', 'User',
    function($scope, User) {
        $scope.users = User.query();

        $scope.columns = [
            { 'field': 'last', 'label': 'Last Name' },
            { 'field': 'first', 'label': 'First Name' },
            { 'field': 'username', 'label': 'Username' },
            { 'field': 'email', 'label': 'Email' },
        ];
        $scope.orderProp = 'last';
        $scope.orderDirection = false;
        $scope.tableSort = function(field) {
            if ($scope.orderProp === field) {
                $scope.orderDirection = !$scope.orderDirection;
            }
            $scope.orderProp = field;
        };
        $scope.tableSortClass = function(field) {
            if ($scope.orderProp === field) {
                if ($scope.orderDirection) {
                    return 'sortDesc';
                }
                return 'sortAsc';
            }
        };
    }]);

It is part of my adminApp that I created. Since there will be other sections that will also use the table sort properties (orderProp, orderDirection) and methods (tableSort, tableSortClass), is there a place I can put these methods so my eventual recordsController will also have access to them?

OK, so I am trying to create it using a service and factory function. This is all new to me so I am not completely sure what I am doing but here is what I have:

adminServices.factory('TableSort', [
    function() {
        var orderProp = 'id';
        var orderDirection = false;

        function sort(field) {
            alert('test');
            if (orderProp === field) {
                orderDirection = !orderDirection;
            }
            orderProp = field;
        }

        function sortClass(field) {
            if (orderProp === field) {
                if (orderDirection) {
                    return 'sortDesc';
                }
                return 'sortAsc';
            }
        }
    }]);

I was hoping to access them in my html using something like ng-click="TableSort.sort(field)" but it doesn't work as it is right now.

3
  • 1
    You could use a Service to do that. Commented Aug 5, 2014 at 14:59
  • 2
    Check out angular services(docs.angularjs.org/guide/services) and directives (docs.angularjs.org/guide/directive) to learn how to isolate and reuse logic. Your sorting logic can be pulled into a service and injected into any controller. Any common DOM manipulation can be reused as a directive. Good luck. Commented Aug 5, 2014 at 15:06
  • You may also add them to a parent $scope, or even $rootScope. Commented Aug 5, 2014 at 15:10

3 Answers 3

1

As stated above in the other posts, you can create a service that you can inject into various controllers to "share" the code.

Below is a full example:

myApp.service('myService', function myService() {
    return {
        someVar: "Value",
        augmentName: function(name){
            return "Sir " + name;
        }
    }
});

This first piece is the service. I've defined a "myService" and given it one function "augmentName" Now you can inject the myService and access the augment name function.

myApp.controller('testCtrl', function ($scope, myService) {

    $scope.testFunction = function(name){
      console.log(myFunction.someVar); //This will access the service created variable
      return myService.augmentName(name);
    }
}

The controller injects the service and then calls it within one of its functions.

Now your HTML code should have access to the controller if you have defined an ng-controller with "testCtrl" or if you have put testCtrl as the controller in your router.

You can now call ng-model="testFunction(someName)" and it will resolve as expected.

Hope that helps. Let me know if you want me to go into greater depth

If you are still trying to figure out how everything in angular works, the angular phone cat tutorial helped me allot when I started out. I'd recommend donating an hour or so into playing with it.

Also, I highly recommend experimenting as early as possible with yeoman/angular generator, this will force you to use angular "the angular way" and can really help you with getting your project set up correctly.

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

2 Comments

OK, I understand most of what you have here. To return an actual variable, should I return variableName: variable?
I edited my code to include a variable on the service. So in the past I have needed some variable that is accesible across multiple controllers, so rather than using a global, you can define variables just like you do functions in services. Then you can access them off of the Service that you injected. You could wrap the variable in getters in setters as well, which is probably a good practice, but I just added the variable to the service.
1

You can use a Service or a Factory to hold these common methods. Additionally, you could use the $rootScope.

Comments

1

You can create a service and put all those properties and method in it. Here is an example for the same:

userControllers.service('UserListControl', function() {
    var orderProp = 'last';
    var orderDirection = false;
    return {
       tableSort : function(field) {
        if (orderProp === field) {
            orderDirection = !orderDirection;
        }
        orderProp = field;
    };
      tableSortClass: function(field) {
        if (orderProp === field) {
            if (orderDirection) {
                return 'sortDesc';
            }
            return 'sortAsc';
        }
    };
   }
});

1 Comment

I added more to my question. I am trying to use a service with factory functions. What is the difference between that and what you are doing? Also, I want to apply it to my whole app, not just the userControllers.

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.