How to pass index value to controller from ng-repeat in Angular - javascript

I am dynamically creating divs, while clicking a button which contains some radio inputs. In the controller I have an array for the divs population which initially has a length of 1.
'use strict';
angular.module('load').controller(
'commodityController',
function($scope, $http, $state, $stateParams) {
$scope.parentload = $scope.$parent.load;
$scope.addMoreCommodities = function() {
$scope.parentload.loadCommodities.push({
'isHazmat' : false,
'dimension' : 'IN'
});
}
$scope.parentload.loadCommodities = []; // emtry array
$scope.addMoreCommodities(); // Here initialize the array
$scope.changeHazmat = function(booleans, val) {
console.log("booleans " + booleans);
console.log("isactive " + val);
$scope.parentload.loadCommodities[val].isHazmat = booleans;
};
});
Using following html, while loading the page div populated well,
<div class="form-right-card disabledInput" ng-init="showname==true" id="commodityContent">
<form name="commodityAttForm">
<div ng-repeat="loadCommodities in load.loadCommodities">
<div class="form-group33"> {{$index}} // here value prints correctly
<label class="form-label">Hazmat</label>
<input type="radio" class="form-btn-inactive" ng-click="changeHazmat('true',$index)" id="yes" name="hazmat" />
<label class="plsLabel" for="yes">Yes</label>
<input type="radio" class="form-btn-inactive" ng-click="changeHazmat('false',$index)" id="no" name="hazmat" />
<label class="plsLabel" for="no">No</label>
</div>
</div>
</form>
</div>
<button class="form-btn-link" ng-click="addMoreCommodities()">+ Add Commodity</button>
I am able to generate the div with all the inputs when clicking on the button. Problem is, I am sending the $index to controller on ng-click of the radio buttons, while clicking on the radio buttons, I am calling the function changeHazmat('true',$index) here the index is always 0, even when I have an array with a length greater than 1.
$scope.changeHazmat = function(selected, val) {
console.log("val" + val);
$scope.parentload.loadCommodities[val].isHazmat = selected;
Log is always printing the index as 0.
Can someone help me here, what am I doing wrong?

You are correctly passing the $index the controller and the code should work.
However I would recommend to use ngModel with ngValue directive.
<input type="radio" ng-model="loadCommodities.isHazmat" ng-value=true name="hazmat" />
(function(angular) {
'use strict';
angular.module('myApp', [])
.controller('Controller', ['$scope', function($scope, ) {
$scope.parentload = {
loadCommodities: []
};
$scope.addMoreCommodities = function() {
$scope.parentload.loadCommodities.push({
'isHazmat': false,
'dimension': 'IN'
});
}
$scope.addMoreCommodities();
$scope.changeHazmat = function(booleans, val) {
$scope.parentload.loadCommodities[val].isHazmat = booleans;
};
}]);
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="Controller">
<div ng-repeat="loadCommodities in parentload.loadCommodities">
<div class="form-group33">
<label class="form-label">Hazmat</label>
<input type="radio" ng-model="loadCommodities.isHazmat" ng-value=true name="hazmat" />
<label class="plsLabel" for="yes">Yes</label>
<input type="radio" ng-model="loadCommodities.isHazmat" ng-value=false name="hazmat" />
<label class="plsLabel" for="no">No</label>
</div>
<p>{{parentload.loadCommodities}}</p>
</div>
</div>
</div>

I'm wondering if the problem is you're assigning the same "id" ('yes' and 'no') to multiple divs (ie inside the loop). It might be the reason the $index isn't working for you. If you remove the id's for the time being and re-try, I'm thinking the problem goes away.

Related

Resolving ng-model outside the form

I have an html file with 2 form elements with input elements inside both. I would be using the ng-if to select which form element I need. The input elements are bound to the same model. But I am unable to resolve it outside the form scope.
<form ng-if="some_name == '1'">
<input ng-model="model_name">
</form>
<form ng-if="some_name == '2'">
<input ng-model="model_name">
</form>
{{model_name}} //This is different from the value of either of the input elements
//it has the initial value which i would assign : $model_name = "xyz"; in my associated js file
The reason you are not able to see those changes outside your form is because you are using 'ngIf' directive to add/remove the DOM and also the 'ngIf' directive creates a new scope.
There are two quick ways to solve this:
1) Make use of 'ngShow'. Look at the below example:
angular.module('app', [])
.controller('HomeController', function($scope) {
$scope.model_name = 'Hi';
$scope.some_name = '1';
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div data-ng-app="app" data-ng-controller="HomeController">
<form ng-show="some_name == '1'">
<input ng-model="model_name">
</form>
<form ng-show="some_name == '2'">
<input ng-model="model_name">
</form>
{{model_name}}
</div>
2) Make the input model an object, instead of a primitive.
angular.module('app', [])
.controller('HomeController', function($scope) {
$scope.model_name = {
value: 'Hi'
};
$scope.some_name = '1';
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div data-ng-app="app" data-ng-controller="HomeController">
<form ng-if="some_name == '1'">
<input ng-model="model_name.value">
</form>
<form ng-if="some_name == '2'">
<input ng-model="model_name.value">
</form>
{{model_name.value}}
</div>

AnjularJS get value of textboxes after button press

I set the values of textboxes via a ajax request in my controller like this :
$http({method: 'GET', url: url}).success(function(data) {
$scope.valzz = data;
$scope.company = $scope.valzz[0].Company;
});
Then in my html :
<label class="item item-input item-stacked-label">
<span class="input-label">Company :</span>
<input type="text" placeholder="Company" value="" ng-model="company">
</label>
<button class="button button-positive" style="margin-top:10px;" ng-click="saveChanges()">
Save Changes
</button>
This correctly puts the company name in the company textbox. But when make a change to that textbox and press the save button, the new value of the textbox isnt showing - it still gets the original. This is the button click in the controller :
$scope.saveChanges=function(){
alert($scope.company);
};
Why is $scope.company not the new value of the textbox? am i doing something wrong? (sorry if basic i am new to angular)
Try removing value=""
HTML:
<label class="item item-input item-stacked-label">
<span class="input-label">Company :</span>
<input type="text" placeholder="Company" ng-model="company">
</label>
<button class="button button-positive" style="margin-top:10px;" ng-click="saveChanges()">
Save Changes
</button>
In corresponding CONTROLLER:
$scope.saveChanges = function() {
alert($scope.company);
};
You don't have a watcher for that model.
$scope.$watch('company', function(company) {
console.log(company);
}
Or in your template, you can interpolate the value:
{{company}}
And then you can see it changing on the html page, because angular make a watcher for it behind the scene
Needed to put this.company not $scope
Please define $scope.company before $http call
app.controller('myCtrl', function($scope, $http){
$scope.company = null; // <--
$http({method: 'GET', url: url}).success(function(data) {
$scope.valzz = data;
$scope.company = $scope.valzz[0].Company;
});
}
Because, once the partials has rendered, it gets only the defined properties in $scope. After that if any property is added inside $scope it needs to call the $apply.
Hope this may help you.
I would assume that you have $scope working properly, and that you have initialized the controller in your app, as well as linked to the proper controller file. Please compare your code to what I have here, as this is working properly.
HTML:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src ="controller.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="testController">
<form>
<label class="item item-input item-stacked-label">
<span class="input-label">Company :</span>
<input type="text" placeholder="Company" ng-model="company">
</label>
<button class="button button-positive" style="margin-top:10px;" ng-click="saveChanges()">
Save Changes
</button>
</form>
</div>
</body>
</html>
Controller:
(function(){
'use strict';
var app = angular.module('myApp', []);
app.controller('testController', [ '$scope', function ($scope){
$scope.saveChanges=function(){
alert($scope.company);
};
}]);
})();
Edit: Fiddle

Adding/Removing checked attribute to checkbox dynamiclly in angularjs

How can i simply add and remove checked attribute to check-box using angularjs.
I've find solution from this question,but it requires Jquery
Is any other way to do this without using Jquery?
Here is what i am tried
<input type="checkbox" id="test" class="switch__input" checked="{{checkVal}}">
<input type="button" ng-click="test()" value="test">
JS
module.controller('settingsCtrl',function($scope){
//for adding
$scope.checkVal="checked";
//for removing checkbox
$scope.test=function(){
$scope.CheckVal="";
}
}
But the removing wont work
This is Angularjs recommended way of check and un check checkbox
HTML :
<input type="checkbox" ng-model="checkVal" ng-true-value="true" ng-false-value="false">
Also works
<input type="checkbox" ng-checked="checkVal">
JS :
module.controller('settingsCtrl',function($scope){
//for adding
$scope.checkVal=true;
//for removing checkbox
$scope.test=function(){
$scope.checkVal=false;
}
}
You don't need special directive for this, ngChecked would work well:
var app = angular.module('demo', []).controller('MainController', function($scope) {
$scope.checkVal = true;
$scope.test = function() {
$scope.checkVal = !$scope.checkVal; // or false
};
});
<script src="https://code.angularjs.org/1.4.3/angular.js"></script>
<div ng-app="demo" ng-controller="MainController">
<input type="checkbox" id="test" class="switch__input" ng-checked="checkVal">
<input type="button" ng-click="test()" value="test">
</div>
Please check working example : DEMO
HTML
<input type="checkbox" id="test" class="switch__input" ng-checked="checkVal">
<input type="button" ng-click="test()" value="test">
Controller:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.checkVal = true;
//for adding/removing checkbox
$scope.test = function() {
$scope.checkVal = !$scope.checkVal;
}
});
I can across a directive to add dynamic attribute may be this can help you
myApp.directive('dynAttr', function() {
return {
scope: { list: '=dynAttr' },
link: function(scope, elem, attrs){
for(attr in scope.list){
elem.attr(scope.list[attr].attr, scope.list[attr].value);
}
//console.log(scope.list);
}
};
});
In the controller
$scope.attArray = [
{ attr: 'myattribute', value: '' }
];
Use it as
<input dyn-attrs="attArray"></input>

How select a check box on loading a page using angular

I have number of check boxes in my single page
<div class="check-outer">
<label>Place of operation</label>
<div class="checkDiv">
<div ng-repeat="place in places">
<div class="checkbox-wrapper">
<label>
<input type="checkbox" ng-model="placesOBJ[place.place_id]">
<span></span>
</label>
</div>
<label class="chk-lbl">{{place.place_name}}</label>
</div>
</div>
</div>
This is working perfectly. If data is present then i want to defaultly check this check boxes
if($scope.client.client_places){
var plcLength = $scope.client.client_places.length;
var client_places = new Array();
for(var i = 0; i < plcLength; i++){
client_places[i] = $scope.client.client_places[i]['place_id'];
}
// console.log(client_places);
//$scope.placesOBJ4 = client_places;
$scope.placesOBJ = client_places;
}
client places contain an array like {1, 2}
But this is not working. if any one know about this please help me.
You can use a directive ng-checked and pass in an expression based on the model
You can use ng-checkedto achieve what you need
<input type="checkbox" ng-model="placesOBJ[place.place_id]" ng-checked="placesOBJ">
If $scope.placesOBJ is populated (not null) then the expression is true and the checkbox will be selected
Just have a look at this simple code It will be useful for you
<body ng-app="myApp" ng-controller="HomeCtrl" ng-init="init()">
<div>
<label>Place of operation</label>
<div ng-repeat="place in places" ng-show="check">
<input type="checkbox" ng-model="placesOBJ[place.id]" ng-checked="true">
<label class="chk-lbl">{{place.name}}</label>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script>
var app=angular.module('myApp', []);
app.controller('HomeCtrl', ['$scope', function($scope) {
$scope.check=false;
$scope.places=[{'id':1, 'name':'place1'},{'id':2, 'name':'place2'},{'id':3, 'name':'place3'},{'id':4, 'name':'place4'}];
$scope.init=function()
{
if($scope.places)
{
$scope.check=true;
}
}
}]);
</script>
</body>
Explanation:- You can make use of ng-init="init()" to call on page load , it will check if data is present or not. If present then set ng-show="true" else by default it will be false

How to check a radio button with angularJS?

I am creating a html / angularjs form. In the form i have a radio button with yes or no. So i want to check by default the button No.
This is the code i use :
My controller :
angular.module('radioExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.myvariable = 'false';
}]);
My html code snippet:
<div class="col-lg-10">
<input type="radio" id="variable" name="variable" ng-model="myvariable" value="true">Yes</input>
<input type="radio" id="variable" name="variable" ng-model="myvariable" value="false">No</input>
</div>
But nothing is selected(checked) when i load the form the first time. I have to click to one value to have one selected (checked)
What's wrong with my code ? Here the plunker link
Thanks
I've made a fiddle for you. Check HERE
You should also set ng-value which should be true or false
<div ng-controller="MyCtrl">
<div ng-repeat="o in options">
<input type="radio" name="group1" ng-model="o.checked" ng-value="o.checked"></input>
<label>{{o.name}}</label>
</div>
</div>
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.options = [
{ name: 'OPT1', id: 1, checked: false },
{ name: 'OPT2',id: 2, checked: false },
{ name: 'OPT3',id: 3, checked: true }
];
}
The reason why it does not work in your plunkr is because you create a module named "radioExample" but you don't use it when you write the HTML code.
Basically, replace this -
<html ng-app>
at the beginning of the code with this
<html ng-app="radioExample">
This way, when you declare the controller, AngularJS knows which module it needs to look into to get the controller.
Note - if you had not associated your controller with a module, then your code would work.
Check out ng-checked. What you have to do is to add ng-app="radioExample" to the html-Tag of your Application.
Then add ng-checked="myvariable == 'false'" and ng-value="'value'" like in the following plunker example:
Plunker
<div class="col-lg-10">
<input ng-checked="myvariable == 'true'" type="radio" id="variable" name="variable" ng-model="myvariable" value="true">Yes
<input ng-checked="myvariable == 'false'" type="radio" id="variable" name="variable" ng-model="myvariable" value="false">No
</div>
Error in data binding. Define myvariable in controller override value in radiobutton. You must use ng-repeat like
<div ng-repeat="o in options">
<input type="radio" name="name" ng-model="o.checked" ng-value="o.checked"></input>
<label>{{o.name}}</label>
</div>
(I use code from previous answer)

Categories

Resources