I have a form with parameterized names like
<div id="form-group">
<label>City</label>
<input class="form-control" id="localityGoogle" disabled="true" ng-model="localityGoogle"></input></td>
</div>
<div id="form-group">
<label>State</label>
<input class="form-control" id="administrative_area_level_1Google" disabled="true" ng-model="administrative_area_level_1Google "></input></td>
</div>
In another function I obtain the values to set in the form. I iterate the structure I obtain to set the values
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
addressTypeGoogle = addressType+'Google';
var val = place.address_components[i][componentForm[addressType]];
$scope.addressTypeGoogle = val;
}
}
I want to know if it is possible to access the values in the scope in a way like this
$scope[addressTypeGoogle] = newValue;
Thank you
$scope is just another JS object. So anything you can do with a regular JS object you can do with scope.
$scope.foo = 'bar';
console.log($scope['foo']); //bar
var propName = 'foo';
console.log($scope[propName]); //bar
All of those are valid.
Related
In my app i have a select html which has following options
"Addition","Deletion","Duplicate","Member Duplicate"
Above drop down page is common for both add and edit screen. As of now if we come from any addition click or edit click drop-down has all options. (Note: drop-down binds at the time of loading page itself. we will show/hide depending on click)
As per new requirement I need to remove all other options except "Addition" in addition click and remove "Addition" option in edit click.
select html:
<select name="ReasonID" required ng-model="member.ReasonID" class="form-control" ng-options="reason.ID as reason.Description for reason in reasons |orderBy: reason.Description"></select>
Js
$scope.manageMember = function (member) {
$scope.showGrid = false;
$scope.showForm = true;
reset();
$scope.memberTemp = member;
angular.extend($scope.member, member); };
Please let me know if you need more details from my end.
Update :
Here the full sample code and working demo with dummy data.
HTML
<div ng-app>
<h2>Todo</h2>
<div ng-controller="TodoCtrl">
<select name="ReasonID" required ng-model="member.ReasonID" class="form-control" ng-options="reason.ID as reason.Description for reason in reasons |orderBy: reason.Description"></select>
<br/>
<input type="button" ng-click="manageMember(undefined)" value="add"/>
<input type="button" ng-click="manageMember('bla bla bla')" value="edit"/>
</div>
</div>
JS
function TodoCtrl($scope) {
$scope.reasons = [{ID:1,Description :"Addition"}, {ID:2,Description :"Deletion"},{ID:3,Description :"Duplicate"},{ID:4,Description :"Member Duplicate"}];
var reasonsTemp =angular.copy($scope.reasons);
$scope.manageMember = function (member) {
console.log(reasonsTemp)
$scope.reasons=reasonsTemp;// assign global object to model
$scope.showGrid = false;
$scope.showForm = true;
$scope.memberTemp = member;
var EditArray=[];
for(var i = 0 ; $scope.reasons.length>i;i++)
{
if($scope.reasons[i].Description === ($scope.memberTemp == undefined ? "Addition" : "bla bla bla"))// condition for is this addition or not
{
EditArray = $scope.reasons[i];
break;
}
else // if is it not addition, then addition only offect that object. because we were already assigned original value globally
{
if($scope.reasons[i].Description!=="Addition")
{
EditArray.push($scope.reasons[i])
}
}
}
$scope.reasons=EditArray;
console.log($scope.reasons);
}
}
Working Demo On console window
Try this,
HTML
<select ng-model="selectedOption">
<option ng-show="reason.show" ng-repeat="reason.ID as reason.Description for reason in reasons |orderBy: reason.Description">{{reason.ID}}</option>
</select>
JS
$scope.manageMember = function (member) {
$scope.showGrid = false;
$scope.showForm = true;
reset();
$scope.memberTemp = member;
angular.extend($scope.member, member);
if(member){
for(var i = 0 ; $scope.reasons.length>i;i++)
{
$scope.reasons[i].show = true;
if($scope.reasons[i].ID == "Addition"){$scope.reasons[i].show = false;}
}
}else{
for(var i = 0 ; $scope.reasons.length>i;i++)
{
$scope.reasons[i].show = false;
if($scope.reasons[i].ID == "Addition"){$scope.reasons[i].show = true;}
}
}
}
Suppose you have two buttons as,
<input type="button" ng-click="toAdd=true">Add</input>
<input type="button" ng-click="toAdd=false">Edit</input>
And the select box code should be like,
<select ng-model="selectedOption">
<option ng-show="toAdd">Addition</option>
<option ng-show="!toAdd">Deletion</option>
<option ng-show="!toAdd">Duplicate</option>
<option ng-show="!toAdd">Member Duplicate</option>
</select>
Hope this helps.
I've been facing an issue since couple of hours. My view template looks like-
<div class="row" ng-repeat="row in CampaignsService.getRows().subItems track by $index">
<div class="col-sm-2">
<select class="form-control dropDownPercent" ng-model="CampaignsService.dropDownPercent[{{CampaignsService.selectCounter}}]" ng-change="CampaignsService.wow(CampaignsService.dropDownPercent, $index)" ng-options="o as o for o in CampaignsService.showPercentDropDown().values">
</select>
</div>
<div class="col-sm-2" style="line-height: 32px">
of visitors send to
</div>
<div class="col-sm-4">
<select class="form-control" ng-model="campaignSelect" ng-options="campaign.Campaign.id as campaign.Campaign.title for campaign in CampaignsService.getRows().items">
<option value=""> Please select </option>
</select>
</div>
<div class="col-sm-4">
<a class="btn btn-default" target="_blank" href="">Show campaign</a>
</div>
Variable CampaignsService.selectCounter is a counter variable and declared in service but when I'm going to use ng-model="CampaignsService.dropDownPercent[{{CampaignsService.selectCounter}}]" it gives me error -
Error: [$parse:syntax] Syntax Error: Token '{' invalid key at column 35 of the expression [CampaignsService.dropDownPercent[{{CampaignsService.selectCounter}}]] starting at [{CampaignsService.selectCounter}}]]
And when I use ng-model="CampaignsService.dropDownPercent['{{CampaignsService.selectCounter}}']" it does not give any error but it takes this variable as string.
My question is how could I create a model array and get model's array values in my service ?? I read many questions in stack community and none of the trick work for me. My service under my script, is
.service('CampaignsService', ['$rootScope', 'AjaxRequests', function ($rootScope, AjaxRequests) {
this.dropDownPercent = [];
this.selectCounter = 0;
var gareeb = [];
this.showPercentDefault = 100;
// this.campaignsData = [];
this.$rowsData = {
items: [], //array of objects
current: [], //array of objects
subItems: [] //array of objects
};
this.getRows = function () {
return this.$rowsData;
}
this.addNewRow = function () {
var wowRow = {}; //add a new object
this.getRows().subItems.push(wowRow);
this.selectCounter++;
gareeb.push(0);
}
this.calculatePercentages = function (index) {
angular.forEach(this.getRows().current, function (data, key) {
if (key == index) {
console.log(data);
}
})
}
this.showPercentDropDown = function ($index) {
var balle = 0;
var start;
angular.forEach(gareeb, function (aha, keywa) {
balle += aha;
})
var last = 100 - balle;
var final = [];
for (start = 0; start <= last; start += 10) {
final.push(start);
}
return this.values = {
values: final,
};
}
this.wow = function (valueWa, keyWa) {
console.log(this.dropDownPercent);
gareeb[keyWa] = valueWa;
this.changePercentDropDown();
}
this.changePercentDropDown = function () {
var angElement = angular.element(document.querySelector('.dropDownPercent'));
angular.forEach(angElement, function (data, key) {
console.log(data);
})
}
}])
Target model structure should be
ng-model="CampaignsService.dropDownPercent[1]"
ng-model="CampaignsService.dropDownPercent[2]"
ng-model="CampaignsService.dropDownPercent[3]"
A big thanks in advance.
Since you are in context of the Angular expression, you don't need interpolation tags {{...}}. So ngModel directive should look like this:
ng-model="CampaignsService.dropDownPercent[CampaignsService.selectCounter]"
I have a similar question like this: setting backbone models but I need to set multiple attributes, not only one.
So, I have a model in which someone can add custom attributes and I have problem setting them, because if I do it this way:
parameter.set({
name: nameValue,
value: valueValue,
description: descriptionValue
});
where name, value and description are string values, backbone is creating a new attribute by the name of "name", "value" and "description", but I actually need them to be values of the "name" etc.
If I try to do it this way:
parameter.set(name, nameValue);
parameter.set(value, valueValue);
parameter.set(description, descriptionValue);
backbone creates only the last line: parameter.set(description, descriptionValue);
the same thing happens when I try to do it this way:
parameter.attributes[name] = nameValue;
parameter.attributes[value] = valueValue;
parameter.attributes[description] = descriptionValue;
so, for example, let's say I have this HTML code:
<input type="text" id="name"/>
<input type="text" id="nameValue"/>
<input type="text" id="value"/>
<input type="text" id="valueValue"/>
<input type="text" id="description"/>
<input type="text" id="descriptionValue"/>
where:
var name = this.$('#name');
var nameValue = this.$('#nameValue');
var value = this.$('#value');
var valueValue = this.$('#valueValue');
var description = this.$('#description');
var descriptionValue = this.$('#descriptionValue');
You can add them like:
var name = this.$('#name').val();
var nameValue = this.$('#nameValue').val();
var value = this.$('#value').val();
var valueValue = this.$('#valueValue').val();
var description = this.$('#description').val();
var descriptionValue = this.$('#descriptionValue').val();
var params = {};
if (name) {
params[name] = nameValue;
}
// the same for other attributes
// ....
// And at the end
model.set(params);
If statement will ensure that attribute names exists. And then collect them into an empty object. At the end set them at once.
Update
Below you can find working example of your issue. Fill the inputs and then click submit to stringify the object you wish to construct.
var MyForm = Backbone.View.extend({
el: '#test',
events: {
"click .submit": "showObject"
},
showObject: function(e) {
e.preventDefault();
var name = this.$('#name').val();
var nameValue = this.$('#nameValue').val();
var value = this.$('#value').val();
var valueValue = this.$('#valueValue').val();
var description = this.$('#description').val();
var descriptionValue = this.$('#descriptionValue').val();
var params = {};
if (name) {
params[name] = nameValue;
}
if (value) {
params[value] = valueValue;
}
if (description) {
params[description] = descriptionValue;
}
this.model.set(params);
this.$('.test-object').text(JSON.stringify(this.model.toJSON()));
}});
var TestModel = Backbone.Model.extend({});
var myForm = new MyForm({model: (new TestModel()) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone.js"></script>
<div id="test">
<input type="text" id="name"/>
<input type="text" id="nameValue"/>
<input type="text" id="value"/>
<input type="text" id="valueValue"/>
<input type="text" id="description"/>
<input type="text" id="descriptionValue"/>
<div class="test-object"></div>
<button class="submit">Show object</button>
</div>
I have created a select tag with multiple to show it as a listbox and not dropdown.
I have a property which should hold the selected schoolclass which consists of multiple properties like: id, schoolclass , subject, schoolclassIdentifier and color.
When I select now an item in the listbox and press the delete button the $scope.activeStep.selectedSchoolclassCodes array contains one string like "Math10b" actually the selectedSchoolclassCodes array should contain an object created from the above properties.
Why is my selected object wrong?
HTML
<div class="col-md-6">
<select size="10" class="form-control col-md-6" multiple ng-model="activeStep.selectedSchoolclassCodes">
<option class="co-md-6" ng-repeat="item in activeStep.schoolclasses" style="background: rgb({{item.color}})" value="{{item.schoolclassCode}}">{{item.schoolclassCode}}</option>
</select>
</div>
CONTROLLER
'use strict';
angular.module('iplanmylessons').controller('EditSchoolclassCodeWizardStepController', function ($scope, wizardDataFactory, SchoolclassCodeViewModel) {
$scope.activeStep.schoolclassCodeColors = [
'255,165,0',
'255,255,0',
'145,240,140',
'0,128,0',
'170,210,230',
'255,190,200',
'240,130,240',
'100,100,255',
'210,210,210',
'255,0,0'
];
$scope.activeStep.selectedSchoolclassCodes = wizardDataFactory.schoolclassCodesAdded[0];
$scope.activeStep.newSchoolclass = "";
$scope.activeStep.newSubject = "";
$scope.activeStep.newSchoolclassIdentifier = "";
$scope.activeStep.schoolclasses = wizardDataFactory.schoolclassCodesAdded;
$scope.activeStep.schoolclassCodeColorsIsOpen = false;
$scope.activeStep.selectedSchoolclassCodeColor = null;
$scope.activeStep.deleteSchoolclassCode = function () {
for (var i = 0; i < $scope.activeStep.selectedSchoolclassCodes.length; i++) {
var index = Enumerable.from( wizardDataFactory.schoolclassCodesAdded).indexOf(function (s) {
return s.schoolclassCode === $scope.activeStep.selectedSchoolclassCodes[i].schoolclassCode;
});
wizardDataFactory.schoolclassCodesAdded.splice(index, 1);
}
$scope.activeStep.selectedSchoolclassCodes = null;
};
$scope.activeStep.schoolclassCode = function () {
return $scope.activeStep.newSubject + $scope.activeStep.newSchoolclass + $scope.activeStep.newSchoolclassIdentifier;
};
$scope.activeStep.setSchoolclassCodeColor = function (item) {
$scope.activeStep.selectedSchoolclassCodeColor = item;
$scope.activeStep.schoolclassCodeColorsIsOpen = false;
};
});
Have you try ng-options? This post has a good explanation of select/ ng-options with array of objects.
Hope it can help.
I have an input field which once filled with a number populates that count of additional input fields. I can't figure out how to get the values inserted in those generated input fields. Any help is appreciated, and oh, I did try various things and even with angular.element, or solely with jquery, but failed, so any explanation on how to do this is welcome.
Here is my jsfiddle, and the code c/p-ed here:
<div ng-controller="MyCtrl">
<input type="text" ng-model="cntInputs" placeholder="#Inputs"><br/>
<input ng-repeat="i in getTimes()" type="text" placeholder="{{i}}" id="input_{{i}}">
<ul>
<li ng-repeat="j in getTimes()">
Inputed value is: {{getValue(j)}}
</li>
</ul>
</div>
js:
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.cntInputs = 0;
$scope.getTimes=function(){
var a = new Array();
for(var i=1; i <= $scope.cntInputs; i++)
a.push(i);
return a;
};
$scope.getValue = function(id){
//here get the value of that inserted in the element with the id of "input_" + id
return angular.element("input_" + id);
}
}
So add ng-model="inputs[i-1]" to your text field
Then in your controller add $scope.inputs= [];
Then in your getValue function: return $scope.inputs[id-1];
If you make your getTimes function 0 based you wouldn't need the -1s
Updated your fiddle: http://jsfiddle.net/7MhLd/60/