Can't access $location when using .controller method in AngularJS

Scott Sword picture Scott Sword · Sep 6, 2013 · Viewed 37.1k times · Source

I'm using ng-submit on a form to push data to a Firebase, everything works as expected. What I would like to do is change views at the same time. On the submit button itself I have ng-click set to execute a function using $location. If I place my changeView function in a .controller method I can't utilize $location (specifically, it says - "Error: 'undefined' is not an object (evaluating '$location.path')"). Any help would be super duper.

// This doesn't work and throws the error
myApp.controller('CtrlName', ['$scope', 'angularFireCollection',
    function($scope, angularFireCollection, $location) {

         $scope.changeView = function(view) {
             $location.path(view);
         }

    }
]);



// This works as expected, but I'm name spacing my functions globally and I will have to change how I'm accessing my Firebase, which isn't really desired.   
function CtrlName($scope, angularFireCollection, $location) {

    $scope.changeView = function(view) {
        $location.path(view);
    }

}

Here is my template:

<form role="form" ng-submit="tactics.add(tactic)">
    <div class="form-group">
        <label>Select Method</label>
            <select class="form-control" ng-model="tactic.type">
                <option>Email</option>
                <option>Display</option>
            <option>SMS</option>
            <option>Print</option>
        </select>
    </div>
    <button type="submit" class="btn btn-success" ng-click="changeView('/my-tactics')">Save</button>
</form>

Answer

m.e.conroy picture m.e.conroy · Sep 6, 2013

You're not injecting the $location object into your controller. It's listed in your function parameters but you forgot to add it to the list before said function.

myApp.controller('CtrlName', ['$scope', 'angularFireCollection','$location',
    function($scope, angularFireCollection, $location) {
        ...
    }]);