我在表单上使用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);
}
}
这是我的模板:
<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>
答案 0 :(得分:36)
您没有将$location
对象注入控制器。它已在您的函数参数中列出,但您忘记在所述函数之前将其添加到列表中。
myApp.controller('CtrlName', ['$scope', 'angularFireCollection','$location',
function($scope, angularFireCollection, $location) {
...
}]);
答案 1 :(得分:4)
另外,不要忘记将$ location添加到您的操作中:
authControllers.controller('AuthRegisterCtrl', ['$scope', '$http', '$location',
function ($scope, $http, $location) {
$scope.master = {};
$scope.save = function (user) {
$scope.master = angular.copy(user);
$http({
method: 'POST',
url: '/angular/auth/register',
data: user
}).success(function (d) {
$location.path('/login');
});
};
}]);
答案 2 :(得分:1)
圣牛我不敢相信我曾经这样做过。 #Facepalm。以下是重定向表单提交的正确方法。
<强>模板强>
<form role="form" ng-submit="vm.submit(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">Save</button>
</form>
控制器
angular.module('MyApp')
.controller('CtrlName', function($scope, $location, $log, angularFireCollection, tactics) {
var vm = this;
vm.submit = function submit(item) {
tactics.add(item)
.then(function(rsp) {
$log.debug('Attempted to add tactic to Firebase', rsp);
$location.path('/my-tactics');
});
};
}
);
值得注意的变化: