Cald Cald - 6 months ago 463
Javascript Question

AngularJS: Call the ng-submit event outside the form

I'm a fish in AngularJS and I have this scenario.

<form>
<input type="text">
</form>
<button type="submit">submit</button>


In normal ways AngularJS provides the ng-submit directive to work as an attribute in the form but I need to call it outside.

So, someone has experienced the same problem? If yes, what you did?

Answer

Please, surround your code with a ng-controller, and use ng-click on buttons out of scope of <form>.

I make a sample on jsfiddle for you... try it:

http://jsfiddle.net/xKkvj/2/

<div ng-app>
    <div ng-controller="Ctrl">
        <form ng-submit="submit()">Enter text and hit enter:
            <input type="text" ng-model="text" name="text" />
            <input type="submit" id="submit" value="Submit" /> <pre>list={{list}}</pre>
        </form>
        <button ng-click="submit()">Submit 2</button>
    </div>
</div>

with js:

function Ctrl($scope) {
    $scope.list = [];
    $scope.text = 'hello';
    $scope.submit = function () {
        if ($scope.text) {
            $scope.list.push($scope.text);
            $scope.text = '';
        }
    };
}
Comments