问题描述:

I need to be able to have multiple inline forms that update into one array after they are saved. They also need to be able keep their values and not reset.

INDEX:

<body ng-app="formExample">

<div ng-controller="ExampleController">

<form-example></form-example>

<form-example></form-example>

<pre>master = {{master | json}}</pre>

<pre>forms = {{forms | json}}</pre>

</div>

FORM:

<form novalidate class="simple-form">

Name: <input type="text" ng-model="user.name" /><br />

E-mail: <input type="email" ng-model="user.email" /><br />

Gender: <input type="radio" ng-model="user.gender" value="male" />male

<input type="radio" ng-model="user.gender" value="female" />female<br />

<input type="button" ng-click="reset()" value="Reset" />

<input type="button" ng-click="update(user)" value="Save" />

</form>

<pre>form = {{user | json}}</pre>

JS:

angular.module('formExample', [])

.controller('ExampleController', ['$scope', function($scope) {

$scope.user = {};

$scope.forms = [];

}]);

angular.module('formExample').directive('formExample', function(){

return {

restrict: 'E',

templateUrl: 'form.html',

scope: {},

controller: function() {

$scope.maseter = {};

$scope.update = function(user) {

$scope.master = angular.copy(user);

$scope.forms.push($scope.master);

};

$scope.reset = function() {

$scope.user = angular.copy($scope.master);

};

$scope.reset();

}

}

});

Basically, this Plunker is a rudimentary concept of what I'm trying to achieve. My biggest problem is that either the ng-clicks don't work, or they only work the first time.

At the moment, ng-model isn't even binding.

网友答案:

I just read today, what the Google guidelines on Angular directives say: "use controller when you want to expose an API to other directives. Otherwise use link."

So, I modified your directive to use link:

angular.module('formExample').directive('formExample', function(){
  return {
    restrict: 'E',
    templateUrl: 'form.html',
    scope: {
      forms: '='
    },
    link: function(scope, elem, attrs) {
      scope.master = {};
      scope.user = {};
      scope.update = function(user) {
        scope.master = angular.copy(scope.user);
        scope.forms.push(scope.master);
      };
      scope.reset = function() {
        scope.user = angular.copy(scope.master);
      };
      scope.reset();
    }
  }
});

Notice that the forms are passed to the directive via:

<form-example forms="forms"></form-example>

For the rest, see Plunker.

I hope this helps!

相关阅读:
Top