Push values to array in controller

时间:2016-10-19 13:41:05

标签: angularjs

I have input fields on the DOM that I'm capturing using ng-model.

In my controller, I have an array:

app.controller('mainCtrl', function() {
    // set an empty array
    self.manualEntry = [];

    /**
     * ensure form validation
     * @returns boolean - ng-disabled value
     */
    self.disableForm = function() {
        if (self.manualEntry.length <= 0) {
            return true;
        }
        else {
            return false;
        }
    };
});

In my view, I have input fields:

<form>
    <input placeholder="John" ng-model="mainCtrl.manualEntry.firstName"/>
    <input placeholder="Smith" ng-model="mainCtrl.manualEntry.lastName"/>
</form>

<button type="submit"
        ng-disabled="mainCtrl.disableForm()"
        title="Submit">Submit
</button>

I thought that $scope automatically updated the model for use in the controller. I thought using dot notation in the DOM would push these values to the array.

When I update these values, the submit button on the form remains disabled (i.e. disableForm() returns true).

How can I push these values to self.manualEntry when they change or are updated on the DOM?

1 个答案:

答案 0 :(得分:0)

我正在对你想要的东西做一个很大的假设,但似乎常规形式验证是这样做的方法。在http://plnkr.co/edit/Nzmk3R8eU0fmbBZRrTBa?p=info进行演示。

控制器代码

var app = angular.module('plunker',[]);

app.controller('MainCtrl', function($scope) {
  // set an empty array
  var self = this;
  self.manualEntry = {};

  //Let HTML5 handle the form validation itself
  self.printInfo = function() {
    console.log(self.manualEntry);
  };
});

HTML代码:

<body ng-controller="MainCtrl as mainCtrl">
  <form ng-submit="mainCtrl.printInfo()">
    <input placeholder="John" ng-model="mainCtrl.manualEntry.firstName" ng-required="true" />
    <input placeholder="Smith" ng-model="mainCtrl.manualEntry.lastName" ng-required="true" />

    <button type="submit" title="Submit">Submit
    </button>
  </form>
</body>