Search code examples
angularjscontrollersubmit

AngularJS 1.5.5 submitting not working when aliasing the controller


I got the code below

<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>

The controller.js is contains the below code

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

Every thing is ok if I avoid to alias the control in HTML

("AddCustomerCtrl as addCust")

Solution

  • You don't use $scope when using the Controller as syntax. Your controller should be:

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

    Note that if you need to access this when a promise resolves you'll need to create a separate local variable because this will no longer be in context when the promise resolves.