0

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

1 回答 1

1

问题是您的表单位于具有您的ng-controller属性的 div 之外。因此表单没有连接到您的mainCtrl控制器并且无法访问该createMeetup功能。

这是一个代码片段,实际上,您需要做的就是在具有ng-controller属性的 div 内移动表单:

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>

于 2015-02-14T00:53:22.370 回答