TLDR: Here's a plnkr of the issue: https://plnkr.co/edit/HfRoCgPfdoZNxmTtDLf7?p=preview
I have a form with checkboxes:
<div class="form-group">
<div class="input-group">
<div class="checkbox">
<label>
<input type="checkbox" ng-model="rental.car2go.airport.berlin"> Berlin
</label>
<br/>
<label>
<input type="checkbox" ng-model="rental.car2go.airport.hamburg"> Hamburg
</label>
<br/>
</div>
</div>
</div>
that is modifying the rental object. This is how the controller looks like:
angular.module('c2gyoApp', []).controller('c2gyoAppController', [
'$scope',
'state',
function($scope, state) {
$scope.airports = [{
"name": "Berlin",
"model": "rental.car2go.airport.berlin"
}, {
"name": "Hamburg",
"model": "rental.car2go.airport.hamburg"
}, ];
$scope.rental = state.rental;
}]).factory('state', function() {
var rental = {
car2go: {
airport: {
berlin: false,
hamburg: false
}
}
};
return {
rental: rental
};
});
Now I want to use ng-repeat:
<div class="form-group">
<div class="input-group">
<div class="checkbox">
<span ng-repeat="airport in airports">
<label>
<input type="checkbox"
ng-model="airport.model">
{{airport.name}}
</label>
<br>
</span>
</div>
</div>
</div>
With ng-repeat the form is modifying the airports object (airports[1].model=true/false and airports[2].model=true/false).
It should only use the string of that airport object(rental.car2go.airport.berlin and rental.car2go.airport.hamburg ) and modify the rental object. I'm looking for a way to pass the string to ng-model, not the airports object. How can I do this?
Edit: removed the directive, new plnkr
The JSON you are changing is:
$scope.airports = [{
"airport": "Berlin",
"model": "rental.car2go.airport.berlin"
}, {
"airport": "Hamburg",
"model": "rental.car2go.airport.hamburg"
}, ];
where `airports[0].model="rental.car2go.airport.berlin", meaning the string rental.car2go.airport.berlin. This string is replaced with TRUE or FALSE. I guess that you were expecting rental.car2go.airport.berlin to be interpreted as a structure, right? Well, it is not a structure but just a string.
Indeed as #Claies suggested I had to copy the value to the rental array. I used a ng-change function for that. New ng-repeat:
<span ng-repeat="airport in airports">
<label>
<input type="checkbox"
ng-model="airport.model"
ng-change="changeAirport(airport)">
{{airport.name}}
</label>
<br>
</span>
In the controller:
$scope.changeAirport = function(airport) {
var airportName = $filter('lowercase')(airport.name);
state.rental.car2go.airport[airportName] = airport.model;
}
Related
I am creating a form, where when the user clicks on the edit button to edit the text, it works fine. But when user clicks on the update button then reload the page it does not show the updated text after reloading the page.
Here is the plunker, that it worked but the code below does not work when page reloads. (I want to do this only with Front-End)
http://plnkr.co/edit/yyDf2SuEvefLWIK13kS4?p=preview
Here is my code.
<div class="people-view">
<h2 class="name">{{people.first}}</h2>
<h2 class="name">{{people.last}}</h2>
<span class="title">{{people.title}}</span>
<span class="date">{{people.date}} </span>
</div>
<div ng-controller="MyCtrl">
<div class="list-view">
<form>
<fieldset ng-disabled="inactive">
<legend>Basic Info</legend>
<b>First Name:</b>
<input type="text" ng-model="people.first">
<br>
<b>Last Name:</b>
<input type="text" ng-model="people.last">
<br>
<b>Email:</b>
<input type="email" ng-model="people.email">
<br>
<b>Phone:</b>
<input type="num" ng-model="people.phone">
<br>
<b>Website:</b>
<input type="text" ng-model="people.website">
<br>
<b>Education:</b>
<input type="text" ng-model="people.education">
<br>
<b>Education Year:</b>
<input type="text" ng-model="people.year">
<br>
<legend>Address</legend>
<b>Street:</b>
<input type="text" ng-model="people.street">
<br>
<b>City:</b>
<input type="text" ng-model="people.city">
<br>
<b>State:</b>
<input type="text" ng-model="people.state">
<br>
<b>Zip:</b>
<input type="text" ng-model="people.zip">
<br>
</fieldset>
<button type="button" class="edit" ng-show="inactive" ng-click="inactive = !inactive">
Edit
</button>
<button type="submit" class="submit" ng-show="!inactive" ng-click="save()">Save</button>
</form>
</div>
</div>
App.js
var app = angular.module("Portal", []);
app.controller('MyCtrl', function($scope) {
$scope.inactive = true;
$scope.save = function() {
$scope.msg = 'Data sent: '+ JSON.stringify($scope.people);
};
});
JSON file
[
{
"id": "0",
"first": "John",
"last": "Smith",
"img": "//placehold.it/100x100",
"title": "Family",
"date": "Joined 4/2/17",
"email": "jsmith#email.com",
"phone": "555-555-5555",
"website": "www.google.com",
"education": "NYU Law",
"year": "2008",
"street": "123 Main Street",
"city": "Los Angeles",
"state": "CA",
"zip": "1234567"
},
]
Controller
app.controller('PeopleController',['$scope', 'people', '$routeParams',
function($scope, people, $routeParams) {
people.success(function(data) {
$scope.people = data[$routeParams.id];
});
}]);
You can try using the prevent default handler:
ng-click="save($event)"
In your controller, you can put:
$scope.save = function (event) {
event.preventDefault();
$scope.msg = 'Data sent: '+ JSON.stringify($scope.people);
}
to make your changes permanent you have to store it to some sort of storage. files is ok but it's not the best choice. So you may consider using local storage. here is good tutorial of how to handle
local-storage. so the controller will be like
app.controller('myCtrl', ['$scope', function($scope){
$scope.people = {
"first": "John",
"last": "Smith"
}
$scope.myObject = JSON.parse(localStorage.getItem('myObject')) || {
first : $scope.people.first,
last : $scope.people.last
};
$scope.updateThingy = function(){
$scope.people.first = $scope.myObject.first;
$scope.people.last = $scope.myObject.last;
localStorage.setItem('myObject', JSON.stringify($scope.myObject));
};
}]);
here is the plunker. Good luck
I want to show a list of movies and add a new movie by adding it to the array.
The html file:
<!-- FOREACH the movies -->
<div ng-controller="homeController" ng-repeat="movie in movies | orderBy : order">
<div class="movie-wrapper">
<h1>{{movie.name}}</h1>
<p>IMDB: IMDB</p>
</div>
</div>
<!-- ADD a new movie to the array -->
<div ng-controller="homeController">
<h3>Add new movie:</h3>
<form name="movieForm" ng-submit="addMovie(movieInfo)">
<div class="form-group new-movie">
<label for="Title">Title:</label>
<input type="text" class="form-control" name="title" ng-model="movieInfo.title">
</div>
<div class="form-group new-movie">
<label for="IMDB">IMDB:</label>
<input type="text" class="form-control" name="imdb" ng-model="movieInfo.imdb">
</div>
<button type="submit" class="btn btn-primary">Add movie</button>
</form>
</div>
The javascript file:
var app = angular.module('movie-app', ["ngRoute"]);
app.controller("homeController", function($scope) {
$scope.movies = getMovies();
// Method to add a new movie
$scope.addMovie = function(movieInfo) {
$scope.movies.push({
name : movieInfo.title,
imdb_url: movieInfo.imdb
});
console.log("Movie added");
}
});
function getMovies() {
return [{
name: 'Inception',
imdb_url: 'http://www.imdb.com/title/tt1375666/'
}];
}
After pressing the submit button, in the console I did not get any error message, but somehow the UI does not get's refreshed.
I think that somehow the controller does not get a reference/bind to the same array or dom element when I'm pushing the new entry.
First of all, i'm pretty sure you should have an error in your console
You make 3 mistakes :
1. You have an error in your getMovies() function (missing curly brackets {})
function getMovies() {
return [{
name: 'Inception',
imdb_url: 'http://www.imdb.com/title/tt1375666/'
}];
}
Why curly brackets are important ?
name and imdb_url are properties object. In JavaScript, an object must have curly brackets before and after. But your function getMovies returns and array of 1 element, so you have to surround your object with brackets []
2. You also have an error when you call console.log (missing quote ")
console.log("Movie added);
3. And the last one : you have to remove the parenthesis }) (the line after console.log)
The result :
angular.module('movieApp', [])
.controller("homeController", function($scope) {
$scope.movies = getMovies();
// Method to add a new movie
$scope.addMovie = function(movieInfo) {
$scope.movies.push({
name: movieInfo.title,
imdb_url: movieInfo.imdb
});
console.log("Movie added");
};
});
function getMovies() {
return [{
name: 'Inception',
imdb_url: 'http://www.imdb.com/title/tt1375666/'
}];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="movieApp" ng-controller="homeController">
<!-- FOREACH the movies -->
<div ng-repeat="movie in movies | orderBy : order">
<div class="movie-wrapper">
<h1>{{movie.name}}</h1>
<p>IMDB: IMDB
</p>
</div>
</div>
<!-- ADD a new movie to the array -->
<div>
<h3>Add new movie:</h3>
<form name="movieForm" ng-submit="addMovie(movieInfo)">
<div class="form-group new-movie">
<label for="Title">Title:</label>
<input type="text" class="form-control" name="title" ng-model="movieInfo.title">
</div>
<div class="form-group new-movie">
<label for="IMDB">IMDB:</label>
<input type="text" class="form-control" name="imdb" ng-model="movieInfo.imdb">
</div>
<button type="submit" class="btn btn-primary">Add movie</button>
</form>
</div>
</div>
i got one sample app from net, which i tried to implement, but it doesn't seem to work, below is the code of app, please help me by fixing it and suggest me how can i make it more better. i am a newbie to Angular.
Jsfiddle : http://jsfiddle.net/eGzZg/
<div id="main" ng-controller="contactDetails">
<label>Name</label>
<input type="text" name="name" ng-model="newcontact.name"/>
<label>Email</label>
<input type="text" name="email" ng-model="newcontact.email"/>
<label>Phone No</label>
<input type="text" name="phno" ng-model="newcontact.phno"/>
<input type="hidden" ng-model="newcontact.id" />
<input type="button" value="Save" ng-click="saveContact()" />
<div id="table">
<div id="thead">
<span>Name</span>
<span>Email</span>
<span>Phone No</span>
<span>Action</span>
</div>
<div id="tbody" ng-repeat="contact in contacts">
<span> {{contact.name}} </span>
<span> {{contact.email}} </span>
<span> {{contact.phno}} </span>
<span> Edit</span>
<span> Delete</span>
</div>
</div>
</div>
<script>
var uid = 0;
function contactDetails($scope) {
//$scope.contacts = [{ id : null, 'name':null, 'phno':null }];
$scope.contacts = [
{ id:0, 'name': 'Viral',
'email':'hello#gmail.com',
'phno': '123-2343-44'
}
];
$scope.saveContact = function(){
alert('sd');
for( i in $scope.contacts){
if($scope.contacts[i].id == $scope.newcontact.id || ($scope.contacts[i].name == $scope.newcontact.name && $scope.contacts[i].phno == $scope.newcontact.phno)){
$scope.contacts[i] = $scope.newcontact;
}else{
$scope.contacts.id = ++uid;
$scope.contacts.push($scope.newcontact);
}
$scope.newcontact = {};
}
}
}
</script>
don't forget to actually include angular and also you forgot ng-app
<body ng-app>
here ya go
Just change $scope.contacts = [{ id : null, 'name':null, 'phno':null }];
to $scope.contacts = [];
Even if you set the properties of the contact elements to null, it still has a single element and thats why there is no text, but the buttons are appearing when the page is loaded.
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>
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