AngularJS: ng-model inside ng-repeat? - angularjs

I'm trying to generate form inputs with ng-repeat.
Note: 'customFields' is an array of field names: ["Age", "Weight", "Ethnicity"].
<div class="control-group" ng-repeat="field in customFields">
<label class="control-label">{{field}}</label>
<div class="controls">
<input type="text" ng-model="person.customfields.{{field}}" />
</div>
</div>
What is the best/correct way to set 'ng-model'? I would like to send it to the server as person.customfields.'fieldname' where fieldname comes from 'field in customFields'.

<div ng-app ng-controller="Ctrl">
<div class="control-group" ng-repeat="field in customFields">
<label class="control-label">{{field}}</label>
<div class="controls">
<input type="text" ng-model="person.customfields[field]" />
</div>
</div>
<button ng-click="collectData()">Collect</button>
</div>
function Ctrl($scope) {
$scope.customFields = ["Age", "Weight", "Ethnicity"];
$scope.person = {
customfields: {
"Age": 0,
"Weight": 0,
"Ethnicity": 0
}
};
$scope.collectData = function () {
console.log($scope.person.customfields);
}
}
You can try it here.
Updated:
For the validation, the trick is to put <ng-form> inside the repeater. Please try.

It should be:
<input type="text" ng-model="person.customfields[field]" />

Any on who ends up here For ng-model inside ng-repeat
http://jsfiddle.net/sirhc/z9cGm/
the above link has good description on how to use it with examples

Try this
ng-model="person.customfields."{{field}}
Moved the double quotes

Related

ngModel checkbox not shown as selected

I'm having some trouble getting a checkbox to display the correct state (checked/unchecked) of my model. I have the following in my controller:
app.controller('PhotosCtrl', ['$scope', function($scope) {
$scope.form = {};
$scope.editPhotos = {
token: $scope.token,
idArray: $scope.idArray
};
}]);
My form looks like this:
<form accept-charset="UTF-8" name="editPhotosForm" ng-submit="submit(editPhotos);" multipart="true" novalidate>
<input name="utf8" type="hidden" value="✓">
<input name="authenticity_token" type="hidden" ng-model="editPhotos.token" ng-init="editPhotos.token='<%= form_authenticity_token %>'">
<div class="results-label"><b>{{total_count}}</b> <span ng-if="total_count == 1">Photo</span><span ng-if="total_count != 1">Photos</span> Found</div>
<div>
<div class="col">
<a ng-repeat="r in results" class="card result-link">
<div class="content result">
<div class="caption">
<input type="checkbox" ng-model="idArray[r.id]">
</div>
<div class="image-container" ng-style="{'background-image': 'url(' + r.image_url + ')'}">
</div>
</div>
</a>
</div>
</div>
</form>
On my repeater element, I call ng-init="idArray[r.id] = 'false'" to initialize a key r.id = 'false' for each item in r. I don't know if I need to do this or not. I've tried the code without it and it makes no difference. I've also tried using ng-value-true and ng-value-false but those don't seem to be working for me.
Most of the other posts I've seen on this issue deal with simple variables (e.g. $scope.someVar = true rather than more complex structures like a hash.
Here is the structure of idArray:
$scope.idArray = {1290: "false", 1291: "true", 1292: "true", 1293: "false", 1294: "false", 1414: "false"};
This is generated by the ng-init in my repeater, since the ids of the photos can't be known beforehand.
Here is what results looks like:
{
id: 1290,
company_id: null,
image_url: "http://s3.amazonaws.com/mybucket/photos/images/000/001/290/original/214.JPG?1432217895"
}
Doing the following
ng-init="idArray[r.id] = 'false'"
You're assigning the string value 'false' into your object.
Can't you deal with that inside your controller?
$scope.idArray = {};
for (var i = 0; i < $scope.results.length; ++i){
$scope.idArray[$scope.results[i].id] = (i%2 == 0);
}
And removing the ng-init="" (which is, according to Angular doc, a bad practice https://docs.angularjs.org/api/ng/directive/ngInit ).
Another thing was the anchor element that was wrapping the checkbox element. This lead to the click event that was not triggered on the checkbox, but only on the anchor.
<div class="col">
<div ng-repeat="r in results" class="card result-link">
<div class="content result">
<div class="caption">
<input type="checkbox" ng-model="idArray[r.id]">
</div>
<div class="image-container" ng-style="{'background-image': 'url(' + r.image_url + ')'}">
</div>
</div>
</div>
</div>
fiddle :
http://jsfiddle.net/patxy/wak7pwwp/

Exclusive options in AngularJS

I have a list of checkbox and one of checkbox has value ALL. Whenever ALL is checked then the others of checkbox will be disabled and unchecked (value is empty). How should I do this in AngularJS? A list of checkbox is generated by using a loop over a data list as following:
<div ng-repeat="item in moduleService.elements">
<input type="checkbox">{{item.value}}
</div>
You could do something like this:
HTML:
<div ng-repeat="item in moduleService.elements">
<input id="{{'checkbox' + $index}}" type="checkbox" ng-disabled="allChecked" ng-model="item.isChecked">
<label for="{{'checkbox' + $index}}">{{item.value}}</label>
</div>
<div>
<input id="allCheckbox" type="checkbox" ng-model="allChecked" ng-click="onAllClicked()">
<label for="allCheckbox">All</label>
</div>
Controller:
var myCtrl = function(moduleService, $scope) {
$scope.onAllClicked = function() {
if(!$scope.allChecked) {
for (var i = 0; i < moduleService.elements.length; i++) {
moduleService.elements[i].isChecked = false;
}
}
}
}
Here is a JSFiddle with similar code: http://jsfiddle.net/robianmcd/W3xeP/
You can use ng-checked, and it makes it sexy.
<input type="checkbox" id="masterCheckbox" ng-model="master">
<div ng-repeat="item in moduleService.elements">
<input type="checkbox" ng-checked="master">{{item.value}}
</div>
Nice and easy and clean. Check out the JSFiddle
you would also need ng-disabled with Zack's answer
<input type="checkbox" id="masterCheckbox" ng-model="master">
<div ng-repeat="item in moduleService.elements">
<input type="checkbox" ng-disabled="master" ng-checked="master">{{item.value}}
</div>

Angular- Creating a directive from existing html content/

Assume
You have html that you can not modify the inner contents of- but you CAN modify the element attributes.
Your goal is to perform 3d transformations on the element that are bidirectionally linked to the value of 3 range inputs.
One input for X rotation, Y Rotation and Z Rotation.
In order to do that, I think I need to use a directive-- but if I use a directive it will erase the existing html...
see this codepen for the current version.
HTML
<html ng-app="truck">
<head></head>
<body>
<section ng-controller="TruckCtl">
<section class="controls">
<fieldset>
<legend>Rotation</legend>
<div>
<label for="xRotation">X:</label>
<input id="xRotation" ng-model="Rotation.x" type="range" min="0" max="360">
<span ng-bind="Rotation.x"></span>
</div>
<div>
<label for="yRotation">Y:</label>
<input name="yRotation" ng-model="Rotation.y" type="range" min="0" max="360">
<span ng-bind="Rotation.y"></span>
</div>
<div>
<label for="zRotation">Z:</label>
<input name="zRotation" ng-model="Rotation.z" type="range" min="0" max="360">
<span ng-bind="Rotation.z"></span>
</div>
</fieldset>
</section>
<section class="wrapper">
<div id="truck" ng-model="Rotation">
</div>
</section>
</section>
</body>
</html>
JS
(function(){
"use strict";
var app = angular.module('truck', []);
app.controller("TruckCtl", function($scope){
$scope.Rotation = {
x: 0,
y: 0,
z: 0
};
});
//no dice v
app.filter("rotate", function() {
return function(input) {
return model.style({
"-webkit-transform" : "rotateX(" + Rotation.x + "deg)"
});
console.log(model);
}
});
//Directives are where I ge lost.
app.directive("Rotation", function(){
return function(scope, element, attrs){
//what do?
}
});
})();
also:
I have no idea why this fiddle doesn't work.
I would recommend to get it working by keeping things simple first. Once you have code that works, you can refactor it out into a filter and directive. The angular docs cover how to implement a directive pretty well, you can basically just copy, paste, and modify. If you have specific questions I'm sure you'll find answers here or elsewhere. As far as simple code to achieve your goal; your controller along with this HTML will rotate as specified:
<div id="truck" style="-webkit-transform: rotateX({{Rotation.x}}deg) rotateY({{Rotation.y}}deg) rotateZ({{Rotation.z}}deg);"></div>
Also, BTW - js convention is to use camelCasing. $scope.Rotation should be $scope.rotation (lowercase r). Use PascalCase for constructors. Although it is purely a preference, you'll find most libraries adhere to this convention.
So the TLDR version is that my nesting was off so my scopes were wrong.
Also I should've been using a factory rather than a filter or a directive.
Working example can be found: here
--one caveat is that it doesn't work until you adjust all the values first.
so just move all of the range sliders to 0 and then change them as you please
html
<section ng-app="truck">
<section id="wrapper" ng-controller="Truck">
<section class="controls">
<fieldset>
<legend>Rotation</legend>
<div>
<label for="xRotation">X:</label>
<input id="xRotation" ng-model="Rotation.x" type="range" min="-100" max="100">
[[Rotation.x]]
</div>
<div>
<label for="yRotation">Y:</label>
<input id="yRotation" ng-model="Rotation.y" type="range" min="-100" max="100">
[[Rotation.y]]
</div>
<div>
<label for="zRotation">Z:</label>
<input id="zRotation" ng-model="Rotation.z" type="range" min="-100" max="100">
[[Rotation.z]]
</div>
</fieldset>
<fieldset>
<legend>Translation</legend>
<div>
<label for="xTranslation">X:</label>
<input id="xTranslation" ng-model="Translation.x" type="range" min="-100" max="100">
[[Translation.x]]
</div>
<div>
<label for="yTranslation">Y:</label>
<input id="yTranslation" ng-model="Translation.y" type="range" min="-100" max="100">
[[Translation.y]]
</div>
<div>
<label for="zTranslation">Z:</label>
<input id="zTranslation" ng-model="Translation.z" type="range" min="-100" max="100">
[[Translation.z]]
</div>
</fieldset>
</section>
<div id="zderp">
<div id="truck" style="-webkit-transform: rotateX([[Rotation.x]]deg) rotateY([[Rotation.y]]deg) rotateZ([[Rotation.z]]deg) translateX([[Translation.x]]px) translateY([[Translation.y]]px) translateZ([[Translation.z]]px)">
</div>
</div>
</section>
</section>
js
var app = angular.module('truck', []).config(function($interpolateProvider){
"use strict";
$interpolateProvider.startSymbol('[[').endSymbol(']]');
});
app.factory('Rotation', function(){
return {
x : '1',
y : '1',
z : '1'
}
});
function TruckCtl($scope, Rotation){
$scope.x = Rotation.x;
$scope.x = Rotation.y;
$scope.x = Rotation.z;
}
function Truck($scope, Rotation){
$scope.x = Rotation.x;
$scope.x = Rotation.y;
$scope.x = Rotation.z;
}

Angular way to collect values from several inputs

I have following trouble. I have several rows with
dynamically generated inputs in AngularJS view. I'm searching
elegant way to get array from this generated inputs.
This is me html:
<div ng-app>
<div ng-controller="TestCtrl">
<input type="button" value="+" ng-click="addNewRow();"/>
<div ng-repeat="item in items"><input type="text" name="key" ng-value="{item.name}"/> : <input type="text" ng-value="{item.value}"/>
<input type="button" value="x" ng-click="removeItem($index);"/>
</div>
<input type="button" value="Test" ng-click="showItems();"/>
</div>
</div>
and this is my javascript code:
function TestCtrl($scope) {
$scope.items = [
{name: "", value: ""}
];
$scope.addNewRow = function () {
$scope.items.push({
name: "",
value: ""
});
};
$scope.removeItem = function (index) {
$scope.items.splice(index,1);
};
$scope.showItems = function() {
alert($scope.items.toSource());
}
};
alert($scope.items.toSource()); will work correct only under Firefox and as you can
see array is empty. I'm searching a way to update array or other angular way
method.
document.querySelector("input[attr]") or jQuery similar is not good idea I think.
Here is working jsFiddle:
http://jsfiddle.net/zono/RCW2k/21/
I would appreciate any advice and ideas.
Best regards.
Use ngModel:
The ngModel directive binds an input,select, textarea (or custom form
control) to a property on the scope using NgModelController, which is
created and exposed by this directive.
Your view should look like:
<div ng-repeat="item in items">
<input type="text" ng-model="item.name"/> :
<input type="text" ng-model="item.value"/>
<input type="button" value="x" ng-click="removeItem($index);"/>
</div>
(As for the use of toSource() in your code, it is not part of any standard - Gecko-only)
Working example: http://jsfiddle.net/rgF37/

Advice on the correct use of ngModel

I' new to AngularJS and have a following ambiguity with usage of ngModel. I want to give to the user possibility to generate unlimited number of "name": "value" pairs. So I generating div with ng-repeat for every element from pair. Here is my html:
<div ng-app>
<div ng-controller="TestCtrl">
<input type="button" value="+" ng-click="addNewRow();"/>
<div ng-repeat="a in range(itemsNumber)"><input type="text" name="key"/> : <input type="text" name="value"/></div>
</div>
</div>
And the JavaScript:
function TestCtrl($scope) {
$scope.itemsNumber = 1;
$scope.range = function() {
return new Array($scope.itemsNumber);
};
$scope.addNewRow = function () {
$scope.itemsNumber++;
}
};
Here is working js fiddle:
http://jsfiddle.net/zono/RCW2k/
I want to have model for this generating items but not sure how to do it.
I would appreciate any ideas and tips.
Best regards.
Edit:
I have create other solution. It can be viewed in this fiddle
http://jsfiddle.net/zono/RCW2k/8/
But is this solution is good idea?
Here is a fiddle: http://jsfiddle.net/RCW2k/13/
You should just create an array on the scope and it's also your model:
controller:
function TestCtrl($scope) {
$scope.items = [{key:"hello",value:"world"}]
$scope.addNewRow = function () {
$scope.items.push({key:"",value:""});
}
};
html:
<div ng-controller="TestCtrl">
<input type="button" value="+" ng-click="addNewRow();"/>
<div ng-repeat="item in items">
<input type="text" name="key" ng-model="item.key"/> :
<input type="text" name="value" ng-model="item.value"/>
</div>
</div>

Resources