3

How do I go about create an element in my controller? e.g. on a click event?

example controller:

function AddCtrl($scope){

    $scope.add = function(){
         // do stuff to create a new element?
    }


}

example view:

<div ng-controller="AddCtrl">

    <button ng-click="add()">Add</button>
    // create <input type="text" ng-model="form.anotherField">

</div>

Any suggestions much appreciated.

4 Answers 4

2

AngularJS is intended to follow MVC - so the controller creating an element in the view doesn't agree with the MVC behavior. The controller should not know about the view.

It sounds as if you want to have a control appear based on some conditional logic. One approach would be to bind to the visibility of the element.

Sign up to request clarification or add additional context in comments.

Comments

2

In Angular, your controllers should not be manipulating the DOM directly. Instead, you should describe the elements you need in your templates, and then control their display with directives, like ng-switch, ng-hide / ng-show, or ng-if, based on your model, ie, your data.

For example in your controller you might do something like:

$scope.showForm = false;

And then in your partial:

<div id="myForm" ng-show="showForm">
    <!-- Form goes here -->
</div>

By switching $scope.showForm between true and false, you will see your myForm div appear and disappear.

Comments

1

This is a classical mistake coming from jQuery moving to Angular or any other MVC library. The way you should think is to let the view react to changes in the scope.

$scope.items = []
$scope.add = function(){
     $scope.items.push({});
}

In the view:

<input type="text" ng-repeat="item in items" ng-model="item.property">

Comments

1

If you want to display an element based on some condition or after the click, use ng-switch: http://docs.angularjs.org/api/ng/directive/ngSwitch

If you want to add multiple elements, create a repeated list of items and add an item to your view-model on clicking the button:

$scope.yourlistofitems = [];
$scope.add = function() {
     $scope.yourlistofitems.push("newitemid");
}

And in the HTML:

<input type="text" ng-repeat="item in yourlistofitems" ng-model="item.property">

1 Comment

I would like to create some new element in the view (non existing on the load), e.g. add another input field for some more data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.