I am trying to call a function on ng-submit to push to an array if I console log the function it clearly works its just on button event the ng-submit does not get called. I have been researching this issue for far to long. I created a codepen for the problem.
http://codepen.io/anon/pen/emVGNb
<html lang="en">
<body ng-app="meanDemo">
<div class="container" ng-controller="mainCtrl as main">
<ul>
<li ng-repeat="meetup in main.meetups">
{{ meetup.name }}
</li>
</ul>
</div>
<form ng-submit="main.createMeetup()">
<input type="text" placeholder="Meetup Name" ng-model="main.meetupName">
<button class="btn btn-primary" type="submit">Add</button>
</form>
Javascript
angular.module('meanDemo', []);
angular.module('meanDemo').controller('mainCtrl', function(){
var vm = this;
vm.meetups = [ { name: 'Ralphs Meetup'}];
vm.createMeetup = function(){
console.log('hello');
vm.meetups.push({ name: vm.meetupName });
vm.meetups.push({ name: 'bobs meetup' });
vm.meetupName = " "
}
vm.createMeetup();
console.log(vm.meetups)
The issue is that your form is outside the div that has your ng-controller
attribute. Therefore the form is not connected the your mainCtrl
controller and has no access to the createMeetup
function.
Here's a code snippet, all you need to do, really, is move the form inside the div with the ng-controller
attribute:
angular.module('meanDemo', []);
angular.module('meanDemo').controller('mainCtrl', function() {
var vm = this;
vm.meetups = [{
name: 'Ralphs Meetup'
}];
vm.createMeetup = function() {
console.log('hello');
vm.meetups.push({
name: vm.meetupName
});
vm.meetups.push({
name: 'bobs meetup'
});
vm.meetupName = " "
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="meanDemo">
<div class="container" ng-controller="mainCtrl as main">
<ul>
<li ng-repeat="meetup in main.meetups">
{{ meetup.name }}
</li>
</ul>
<form ng-submit="main.createMeetup()">
<input type="text" placeholder="Meetup Name" ng-model="main.meetupName">
<button class="btn btn-primary" type="submit">Add</button>
</form>
</div>
</body>