Friday, October 13, 2017

taking inputs for single controller from multiple input boxes in angular

Two input boxes

Two input boxes

I am building an angular app. User inputs the number of input boxes he wants to create. Accordingly, I have an arrangement of a button and an input box with it and similar number arrangements as per the user input.

I take an example where 2 input boxes are created.

Now the functionality is – toggle enable/disable an input box when button on left of it is clicked.

<div ng-app="myApp" ng-init="isDisabled=true" ng-controller="myCtrl">

<button ng-click="toggledit()">Item A</button>
<input type="text" ng-disabled="isDisabled">

<button ng-click="toggledit()">Item B</button>
<input type="text" ng-disabled="isDisabled">

</div>

I have created the following controller for the required functionality :

<script>
            var app = angular.module('myApp',[]);
            app.controller('myCtrl',function($scope){

                $scope.toggledit = function(){
                   $scope.isDisabled = !$scope.isDisabled;

                };
            });

</script>

As clear from my code, a single controller is controlling both of my input boxes but since this is the case, clicking on 1st button enables/disables the input box for 2nd button also.

My code can have multiple input boxes and functionality for all of them is same so “I want a single controller to control all boxes” but I want a setup where clicking on a button enables/disables only the input box with it and not others.

One way is to pass distinct arguments with my toggledit() function on click of a particular button to identify which button is clicked,give separate distinct scope variable names to ng-disabled and give separate piece of code for each input box. But having multiple input boxes like 30-40 is complicating this task.

Also having separate scope variable names for different input boxes in my code is not possible at the start as number of input boxes is displayed according to what user inputs.They can only be dynamically assigned.

In all, since my input boxes are being created dynamically acc. to user input, I want some kind of setup where dynamically different scope variables are assinged to ng-disabled for different input boxes created and a single controller toggles whatever input box I interact with .

How can I achieve this with angular?

Note:- Above provided code is demo and only a part of my actual code.I am new to angular framework.

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/10/13/taking-inputs-for-single-controller-from-multiple-input-boxes-in-angular/
via @lzomedia #developer #freelance #web #lzomedia.com

No comments:

Post a Comment