AngularJS 1.5.5 别名控制器时提交不工作

AngularJS 1.5.5 submitting not working when aliasing the controller

我得到了下面的代码

<form ng-submit="addCust.submit()" ng-controller="AddCustomerCtrl as addCust"> 
    <div> <input type="text" ng-model="addCust.cName" required/> </div> 
    <div> <input type="text" ng-model="addCust.cCity" required/> </div>
    <div> <button id="f1" type="submit" >Add Customer</button> </div>
</form>

controller.js 包含以下代码

helloWorldControllers.controller('AddCustomerCtrl', ['$scope', '$location',
    function AddCustomerCtrl($scope, $location) {
        $scope.submit = function(){ console.log('AddCustomerCtrl.submit !');
        $location.path('/addedCustomer/' + $scope.cName + "/" + $scope.cCity); }; 
    }
]);

如果我避免在 HTML

中为控件设置别名,一切都很好
("AddCustomerCtrl as addCust")

在使用 Controller as 语法时不使用 $scope。您的控制器应该是:

helloWorldControllers.controller('AddCustomerCtrl', ['$location',
    function AddCustomerCtrl($location) {
        this.submit = function(){ 
            console.log('AddCustomerCtrl.submit !');
            $location.path('/addedCustomer/' + this.cName + "/" + this.cCity); 
        }; 
    }
]);

请注意,如果您需要在 promise 解析时访问 this,您将需要创建一个单独的局部变量,因为当 promise 解析时,this 将不再处于上下文中。

尝试使用以下控制器代码:

helloWorldControllers.controller('AddCustomerCtrl', ['$scope', '$location',
     function ($scope, $location) {
        var addCust = this;
        addCust.submit = function(){
            console.log('AddCustomerCtrl.submit !');
            $location.path('/addedCustomer/' + $scope.cName + "/" + $scope.cCity);
        }; 
    }
]);

当您使用 controllerAs 属性时,到处都是用别名引用的。所以你的代码中应该有 addCust.cName 和 addCust.cCity 。我建议根本不要将 $scope 注入到您的控制器中,并从代码中删除对它的所有引用。如果您不熟悉它,普遍接受的最佳实践在此处有详细记录:https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md.

helloWorldControllers.controller('AddCustomerCtrl', ['$scope', 
     function ($location) {
        var ctrl= this;
        ctrl.submit = function(){
            console.log('AddCustomerCtrl.submit !');
            $location.path('/addedCustomer/' + $ctrl.cName + "/" + ctrl.cCity);
        }; 
    }
]);