在AngularJS中使用.controller方法时无法访问$ location

Sco*_*ord 14 controller angularjs firebase angularfire

我在表单上使用ng-submit将数据推送到Firebase,一切都按预期工作.我想做的是同时改变观点.在提交按钮本身我有ng-click设置来使用$ location执行一个函数.如果我将changeView函数放在.controller方法中,我就无法使用$ location(具体来说,它说 - "错误:'undefined'不是一个对象(评估'$ location.path')").任何帮助都是超级的.

// 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);
    }

}
Run Code Online (Sandbox Code Playgroud)

这是我的模板:

<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>
Run Code Online (Sandbox Code Playgroud)

m.e*_*roy 36

您没有将$location对象注入控制器.它已在您的函数参数中列出,但您忘记在所述函数之前将其添加到列表中.

myApp.controller('CtrlName', ['$scope', 'angularFireCollection','$location',
    function($scope, angularFireCollection, $location) {
        ...
    }]);
Run Code Online (Sandbox Code Playgroud)