简体   繁体   中英

Add new AngularJS variables with JavaScript

I'm trying to make a dynamic form with AngularJS and JavaScript. The objective is to add how many inputs the user need and transform all those inputs in AngularJS variables that print it on body. So I got that code:

$(function(){
   var number = 1;
   $('a.add').click(function(e){
      e.preventDefault();
      $('#this_div_contains_settings').append('<input type="text" name="example'+number+'" ng-model="example'+number+'" placeholder="Anything">');
      number++;
   });
   $('#this_div_contains_settings').on('click','a.design_button', function(e){
      e.preventDefault();
      $(this).parent().remove();
   });
});

This function add a INPUT on my DIV with the different ng-model every time it run.

The problem is, it just work's if the {{example1}} is already on my BODY, if I add it later with another function, it just doesn't work.

I'm new with AngularJS, so I didn't understand if I need to "refresh" the AngularJS everytime I add new variable or something like that.

Any help will be appreciated :)

Using jQuery is the wrong way to solve this problem. Instead, create an array inside of your controller that will hold the models for all of these inputs.

Depending on how you define/create your controllers, $scope may be replaced with this

$scope.examples = [];

Next, create a function that will add a new example to the array:

$scope.addExample = function () {
    $scope.examples.push("");
}

Now, in your template, create the inputs using an ng-repeat:

<div id="this_div_contains_settings">
    <input ng-repeat="example in examples" type="text" name="example" ng-model="example" placeholder="Anything">
</div>

and have your "add" button call your addExample function on click:

<a class="add" ng-click="addExample()">Add Example</a>

Finally, remove all of the code that was included in your question.

And for your .design_button that removes all the examples, that's easy too:

<a class="design_button" ng-click="examples = []">remove all examples!</a>

by that same concept, you could even remove the need for the addExample function, however i tend to keep logic in the controller (well, actually in the services, but that's another topic) anyway rather than putting it in the template.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM