Daveus
Daveus

Reputation: 121

Change the type input dynamically

Hello I have a strange question. I have to create a form but the fields are different for every user so they could be a or . I tried with angular to do something like that

<div ng-controller="myCtrl" ng-repeat="x in prova">
    <input type = "{{x}}">
</div>

And a controller like this

app.controller('controller',['$scope', function($scope){
    $scope.prova = [
        'text',
        'check-box'    
    ]
});

But as I thought it doesn't work.

Thank you for your help.

Upvotes: 0

Views: 82

Answers (4)

Roh&#236;t J&#237;ndal
Roh&#236;t J&#237;ndal

Reputation: 27192

Some code Changes :

  • replace check-box with checkbox.
  • replace controller with myCtrl in the controller function.

Working demo :

Controller :

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

myApp.controller('myCtrl', function($scope) {
    $scope.prova = [
        "text",
        "checkbox"    
    ]
});

View :

<div ng-app="myApp" ng-controller="myCtrl">
  <div ng-repeat="x in prova">
    <input type = "{{x}}">
</div>
</div>

Upvotes: 0

MoMo
MoMo

Reputation: 1876

plunkr included

It works for me. Here is a very simple example in plunkr that mimic's your code.

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';

  $scope.arrTypes = ['submit', 'text', 'button', 'password', 'month'];
});

and in the index.html...:

<div ng-repeat = "inpType in arrTypes">

    <input type={{inpType}} name="" id="" value={{inpType}} />
</div>

Upvotes: 0

Sai
Sai

Reputation: 2658

You missed the closing square bracket of dependency injection. This would work.

app.controller('controller',['$scope', function($scope){
      $scope.prova=[
        'text',
        'check-box'    
      ]
}]);

Upvotes: 0

estacks
estacks

Reputation: 104

You can use the ng-switch directive to only render the correct input type when its type matches x.

<div ng-controller="myCtrl" ng-repeat="x in prova" ng-switch="x">
<input type="text" ng-switch-when="text">
<input type="checkbox" ng-switch-when="check-box">
<textarea ng-switch-when="textarea"></textarea>
</div>

More info: https://docs.angularjs.org/api/ng/directive/ngSwitch

Upvotes: 2

Related Questions