How to convert AngularJS scope object into simple JS array? - javascript

How to convert AngularJS scope object into simple JS array?
This function checks if any checkbox is checked and adds corresponding value to an object.
Now I want to transfer the object values to an array and alert it after press the button. But the result is undefined, why?
var formApp = angular.module('formApp', [])
.controller('formController', function($scope) {
// we will store our form data in this object
$scope.formData = {};
});
var array = Object.keys(formData).map(function(k) { return obj[k] });
function test(){
alert(array);
}
<-- index.html -->
<!DOCTYPE html>
<html>
<head>
<!-- CSS -->
<!-- load up bootstrap and add some spacing -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<style>
body { padding-top:50px; }
form { margin-bottom:50px; }
</style>
<!-- JS -->
<!-- load up angular and our custom script -->
<script src="http://code.angularjs.org/1.2.13/angular.js"></script>
<script src="app.js"></script>
</head>
<!-- apply our angular app and controller -->
<body ng-app="formApp" ng-controller="formController">
<div class="col-xs-12 col-sm-10 col-sm-offset-1">
<h2>Angular Checkboxes </h2>
...
<!-- MULTIPLE CHECKBOXES -->
<label>Favorite Colors</label>
<div class="form-group">
<label class="checkbox-inline">
<input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red"> Red
</label><br>
<label class="checkbox-inline">
<input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.blue"> Blue
</label> <br>
<label class="checkbox-inline">
<input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.green"> Green
</label>
</div>
...
<!-- SHOW OFF OUR FORMDATA OBJECT -->
<h2>formData_object_is_not_empty-test</h2>
<pre>
{{formData}}
</pre>
<button onclick="test()">Click me</button>
</div>
</body>
</html>

Try this:
var formApp = angular.module('formApp', [])
.controller('formController', function($scope) {
// we will store our form data in this object
$scope.formData = {};
var array = Object.keys($scope.formData).map(function(k) { return obj[k] });
// wait for the formData to change and then alert
setTimeout(function() {
alert(array);
}, 2000);
});
Angular is made in a way that you are not allowed to access the scope variables outside the controller.
If you want to have the array as debug information, use a browser plugin like AngularJS Batarang or use console.log(array) instead of alert(array) or try to save array in a global variable with document.array = array, so you can access it in the browser console.

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>

Why is my angular script running an infinite loop?

What I am trying to do is check three boxes via event click upon page load with the use of for loop. What happens is it runs an infinite loop then the page hangs. Here is the code:
<!DOCTYPE html>
<html >
<head>
<link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
</head>
<body ng-app="ngToggle">
<div ng-controller="AppCtrl">
<input type="checkbox" ng-model="dean" ng-click="btnChange($event, values, 1)" id="check-1" name="one" class="here" >
<input type="checkbox" ng-model="armada" ng-click="btnChange($event, values, 2)" id="check-2" name="one" class="here" >
<input type="checkbox" ng-model="armada" ng-click="btnChange($event, values, 2)" id="check-3" name="one" class="here" >
<!--<p ng-repeat="btn in btns">-->
<!-- <input type="checkbox" ng-model="btn.bool" class="here" > {{ btn.value }}-->
<!--</p>-->
{{btn }}
{{values }}
</div>
<script type="text/javascript">
angular.module('ngToggle', [])
.controller('AppCtrl',['$scope', '$timeout', function($scope, $timeout){
$scope.btns = [{}, {}, {}];
$scope.values = [];
$scope.btnChange = function(event, model, val){
_this = angular.element(event.target);
x = _this.prop("checked");
if(x){
model.push(val);
}else{
index = model.indexOf(val);
model.splice(index, 1);
}
};
ids = [1, 2, 3];
$timeout(function() {
for(x=0;x<ids.length;x++){
angular.element("#check-"+ids[x]).trigger("click");
}
}, 1000);
}]);
</script>
</body>
</html>
Here is the plunker: http://plnkr.co/edit/7DpCvkKLlKhRc3YwFTq0?p=info
PS
If you comment or removed the angular.element trigger this will not occur. If someone can provide a code that will trigger the click events on the checkboxes via loop. THEN IT WILL BE GREAT
You can do it the Angular way by setting default values to your checkboxes:
As you use ng-model, in your controller, just set dean and armada to true.
UPDATE:
I've nevertheless debugged your JS. Here is a plunker of your function working. I've used y in the loop (x was already defined) and change a bit the condition of looping.
Anyway, I would recommend you to do with Angular... :-)

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 set ng-model Value via ng-init or value tag

I want to set ng-model Value. I tried with ng-init and value tag.
My code:
Init
{{formObject.consultantId}} // value prints
<input type="hidden" data-ng-model="formObject.consultant.id" data-ng-init="formObject.consultant.id=formObject.consultantId">
{{formObject.consultant.id}} // no data Prints
Value
{{formObject.consultantId}} // value prints
<input type="hidden" data-ng-model="formObject.consultant.id" value="{{formObject.consultantId}}">
{{formObject.consultant.id}} // no data Prints
This works for me
<input type="hidden" data-ng-model="formObject.consultant.id" data-ng-init="formObject.consultant.id='test'">
{{formObject.consultant.id}} // prints as test
Whats wrong in my code ? How to initialize this Value to Model ?
EDIT
I found my issue. This code works for me in Normal Html Form.
But above codes are in ModelForm(directive).
you should change {{formObject.consultantShare.consultant.id}} to {{formObject.consultant.id}} (to OP's edit, now removed)
Take a look at this
var app = angular.module('myApp', []);
app.controller('Controller', function ($scope) {
$scope.formObject = {};
$scope.formObject.consultant = {};
$scope.formObject.consultantId = "254";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp' ng-controller="Controller">{{formObject.consultantId}} // value prints
<input type="hidden" data-ng-model="formObject.consultant.id" data-ng-init="formObject.consultant.id=formObject.consultantId" />{{formObject.consultant.id}}
<br/>{{formObject.consultantId}} // value prints
<input type="hidden" data-ng-model="formObject.consultant.id" value="{{formObject.consultantId}}"/>{{formObject.consultant.id}}
</div>
Can you share your controller to see how formObject is initialized. Meanwhile I have added
var myapp= angular.module('myForm',[]);
(function(){
angular.module('myForm').controller('formController',[formController]);
function formController(){
var vm = this;
vm.formObject = {consultantId:10,consultant:{consultantId:''}};
}
})();
<!DOCTYPE html>
<html ng-app="myForm">
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div ng-controller="formController as vm">
<span>formObject.consultantId:{{vm.formObject.consultantId}}</span>
<input type="hidden" ng-model="vm.formObject.consultantId" ng-init="vm.formObject.consultant.consultantId=vm.formObject.consultantId"
</br>
<span>formObject.consultant.consultantId: {{vm.formObject.consultant.consultantId}}</span>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="formController.js"></script>
</body>
</html>
my solution at : http://plnkr.co/edit/q4d8ZVXz3ki02EjkNZ0n

Clone elements in angularjs

I need to duplicate some input fields in order to handle data from clients. I have done it with jQuery http://jsfiddle.net/m7R3f/1/
HTML:
<fieldset id="fields-list">
<div class="pure-g entry">
<div class="pure-u-1-5">
<input type="text" class="pure-input-1" id="input-1" name="input-1">
</div>
<div class="pure-u-1-5">
<input type="text" class="pure-input-1" id="date" name="date">
</div>
<div class="pure-u-1-5">
<input type="text" class="pure-input-1" id="input-2" name="input-2">
</div>
</fieldset>
<button id="add">Add</button>
JS
$(document).ready(function ()
{
$("#add").click(function ()
{
$(".entry:first").clone(false).appendTo("#fields-list");
});
});
However I just start learning Angular and want to convert these code to Angular.
I have read questions in stackoverflow and found the code with angularjs here: http://jsfiddle.net/roychoo/ADukg/1042/. However, it seem works only for ONE input field? Can I clone/duplicate several input fields using AngularJS? (in other word: convert my code above into AngularJS version?)
Thank you very much.
If you want to clone html element, the best way to use ng-repeat directive.
Your Controller
var App = angular.module('App', []).controller('Test', ['$scope',
function($scope) {
$scope.inputCounter = 0;
$scope.inputs = [{
id: 'input'
}];
$scope.add = function() {
$scope.inputTemplate = {
id: 'input-' + $scope.inputCounter,
name: ''
};
$scope.inputCounter += 1;
$scope.inputs.push($scope.inputTemplate);
};
}
])
<!DOCTYPE html>
<html ng-app="App">
<head lang="en">
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="Test">
<fieldset id="fields-list">
<div class="pure-g entry" ng-repeat="input in inputs track by input['id']">
<div class="pure-u-1-5">
<input type="text" class="pure-input-1" id="input" name="input-1">
</div>
<div class="pure-u-1-5">
<input type="text" class="pure-input-1" id="date" name="date">
</div>
<div class="pure-u-1-5">
<input type="text" class="pure-input-1" id="input-2" name="input-2">
</div>
</div>
</fieldset>
<button type="button" id="add" ng-click="add()">Add</button>
</body>
</html>
Angular prevents of creation duplicated elements, to avoid this, use track by like in the example
You should create an array and use ng-repeat in your HTML. Each object in the array can contain the data necessary to populate your divs. If you want to start with three entries, then add the data for those three. If you want to add more, then simply push onto the array. Because of Angular's 2-way data binding your form field will appear once the element is pushed onto the array.
For more details on how to do this, checkout the To Do example on Angular's home page.
How about this(Fiddle)
add two more ng-model and push those models
$scope.add = function(){
$scope.items.push($scope.newitem1,$scope.newitem2,$scope.newitem3);
}

Categories

Resources