Adding Object in JSON dictionary in AngularJS - javascript

How can I add a new object which be read from input form in AngularJS ?
my JSON :
{
"1": {
"name": "Audi",
"year": "1993",
},
"2": {
"name": "BMW",
"year": "2012",
}
}
my Add.html:
<form name="addForm" ng-controller="AddCtrl" ng-submit="AddCtrl.newcar.(car)">
<p>name: <input type="text" ng-model="AddCtrl.newcar.name"></p>
<p>year: <input type="text" ng-model="AddCtrl.newcar.year"></p>
<input type="submit" value="send" />
</form>
my AddCtrl :
angular.module('motoApp')
.controller('AddCtrl', ['$scope','$http', '$routeParams', function($scope, $http,
$routeParams) {
$http.get('scripts/controllers/cars.json').success (function(data){
});
this.newcar = {};
this.addCar = function(car) {
car.name.push(this.name);
this.newcar ={};
};
}]
);
I want to have page that after filling all inputs and cliking submit button new car will be added in JSON with next id. Where and what should I add to have achieve this ?

Your code is wrong.
angular.module('motoApp')
.controller('AddCtrl', ['$scope','$http', '$routeParams', function($scope, $http,
$routeParams) {
$scope.cars = [];
$http.get('scripts/controllers/cars.json').success (function(data){
$scope.cars = data;
});
$scope.addCar = function() {
$scope.cars.push($scope.car.name);
};
}]
);
form
<form name="addForm" ng-controller="AddCtrl" ng-submit="addCar()">
<p>name: <input type="text" ng-model="car.name"></p>
<p>year: <input type="text" ng-model="car.year"></p>
<input type="submit" value="send" />
</form>
Working fiddle:http://jsfiddle.net/wyorodt0/

Related

AngularJS - unwated binding

I tried to extend the "Heros" application from the AngularJS documentation
I wanted to add the functionality of creating/adding a hero.
In the HeroList.js from this plunk I am able to add a new hero after clicking the button Add from the HeroList.html.
However, if I'm updating the input fields (let's say name) they get edited in the list as well.
For example, if I added a new hero (Captain America), click Add, and then type Robby, Captain America will be concatenated with Robbie.
(function(angular) {
'use strict';
function HeroListController($scope, $element, $attrs) {
var ctrl = this;
// This would be loaded by $http etc.
ctrl.list = [
{
name: 'Superman',
location: ''
},
{
name: 'Batman',
location: 'Wayne Manor'
}
];
ctrl.create = function(hero) {
ctrl.list.push(hero);
};
ctrl.updateHero = function(hero, prop, value) {
hero[prop] = value;
};
ctrl.deleteHero = function(hero) {
var idx = ctrl.list.indexOf(hero);
if (idx >= 0) {
ctrl.list.splice(idx, 1);
}
};
}
angular.module('heroApp').component('heroList', {
templateUrl: 'heroList.html',
controller: HeroListController,
bindings: {
onCreate: '&'
}
});
})(window.angular);
Your Problem is that you are having reference to same Hero Object so when you update the text fields it will automatically update it in the list. To Avoid this problem you can use angular.Copy()
ctrl.create = function(hero) {
ctrl.list.push(angular.copy(hero));
};
this will create separate copy to be added to the list.
here is some code you can refer https://plnkr.co/edit/?p=preview
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-forms-simple-production</title>
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
</head>
<body ng-app="formExample">
<div ng-controller="ExampleController">
<form novalidate class="simple-form">
<label>Name: <input type="text" ng-model="user.name" /></label><br />
<label>E-mail: <input type="email" ng-model="user.email" /></label><br />
Best Editor: <label><input type="radio" ng-model="user.preference" value="vi" />vi</label>
<label><input type="radio" ng-model="user.preference" value="emacs" />emacs</label><br />
<input type="button" ng-click="reset()" value="Reset" />
<input type="submit" ng-click="update(user)" value="Save" />
</form>
<pre>user = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
<script>
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.master = {};
$scope.update = function(user) {
$scope.master = angular.copy(user);
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
}]);
</script>
</body>
</html>
<!--
Copyright 2018 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
-->

authentication with angular js / json

i tried to make login form with angular js
i have list of user in json file but i can't comapre with the input text from login form
User.json :
[{
"username": "user1",
"password": "pass1"
}, {
"username": "user2",
"password": "pass2"
}, {
"username": "user3",
"password": "pass3"
}, {
"username": "user4",
"password": "pass4"
}]
script.js
var app1 = angular.module('app1', []);
var app2 = angular.module('app2', []);
var app = angular.module('app', ['app1', 'app2']);
app1.controller('jsonCtrl', function($scope, $http) {
$http.get('data.json')
.then(function(res) {
$scope.users = res.data;
});
});
app2.controller('formCtrl', function($scope) {
$scope.login = function() {
if ($scope.username == 'test' && $scope.password == 'test') {
alert('valid username/password ' + $scope.username);
alert('user from json ' + $scope.users);
} else {
alert('invalid username/password ' + $scope.username);
}
};
});
index.html
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="script.js"></script>
<body ng-app="app">
<div ng-controller="formCtrl">
<form name="form">
First Name:<br>
<input type="text" ng-model="username"><br>
Last Name:<br>
<input type="text" ng-model="password">
<br><br>
<button ng-click="login()">LOGIN</button>
</form>
</div>
<div ng-controller="jsonCtrl">
<ul>
<li ng-repeat="user in users">
{{user.username}} / {{user.password}}
</li>
</ul>
</div>
</body>
</html>
the problem is replace if ($scope.username == 'test' && $scope.password == 'test') with anything compare with json
this my code : Plunker
You were using two different scopes across application. I moved all your markup under the same controller, so that is more simple manage the bindings.
Take a look at this plnkr
var app = angular.module('app', []);
app.controller('formCtrl', function($scope, $http) {
$http.get('data.json')
.then(function(res) {
$scope.users = res.data;
});
$scope.login = function() {
var u = $scope.users.filter((item) => {
return item.username == $scope.username;
});
if (u[0] && u[0].password == $scope.password) {
alert('correct');
} else {
alert('wr0ng');
}
};
});
<div>
<form name="form">
First Name:
<br>
<input type="text" ng-model="username">
<br> Last Name:
<br>
<input type="text" ng-model="password">
<br>
<br>
<button ng-click="login()">LOGIN</button>
</form>
</div>
<div>
<ul>
<li ng-repeat="user in users">
{{user.username}} / {{user.password}}
</li>
</ul>
</div>
First of all, you should not authenticate user using clear text like that. Your server should do it with hashing table without knowing what is the real password.
Http.get is not synchronous which means that your application will continue its path without waiting for your data. In your plunker your formCtrl doesnt have access to jsonCtrl scope.
You should load your data in a service because it is initialised only once compared to the controller who are initialised everytime you load the page.
Finally you should start by looking at ui.router resolve, it allow you to load your data to your service before the page is displayed which will allow you to compare later.

Cannot get ng-model binding value

I'm using ionic to build a webapp, and I want to use ng-model bind input form value.
It is weird that I am not getting model.cellphone's value, but I got model.password's value.
Currently I cannot figure this out. Can anybody help me?
html:
<ion-view>
<ion-content class="login-content">
<div class="login-form">
<input type="text" class="login-form-cellphone" ng-model="model.cellphone" placeholder="please input your phonenumber" required minlength="11" maxlength="11"/>
<input type="password" class="login-form-password" ng-model="model.password" placeholder="please input your password" required/>
<button class="login-form-btn" ng-click="login()">Login</button>
</div>
</ion-content>
</ion-view>
js:
.controller('LoginCtrl', ['$scope', '$state', '$stateParams', 'RouteService', 'ApiService', function ($scope, $state, $stateParams, RouteService, ApiService) {
var route = 'app.home.login';
var params = $stateParams;
$scope.model = {};
$scope.doRefresh = function () {
$scope.isChecked = true;
};
$scope.goBack = function () {
$state.go(params.previewRoute);
};
$scope.clickCheck = function () {
$scope.isChecked = !$scope.isChecked;
};
$scope.login = function () {
console.log($scope.model.cellphone, $scope.model.password, $scope.isChecked);
if (!$scope.model.cellphone) {
console.log('cellphone');
return;
}
if (!$scope.model.password) {
console.log('password');
return;
}
if (!$scope.isChecked) {
console.log('isChecked');
return;
}
ApiService.login(
$scope.model.cellphone,
$scope.model.password,
null,
function (status) {
if (status === 1)
$state.go(params.previewRoute);
})
};

Testing $scope variables in angularjs

I have a piece of angular code like below:
$scope.someFunction = function(){
$scope.val = $scope.value2.length;
}
I would like to test the above piece of code, for which i am doing something like below:
describe('test that', function() {
beforeEach(module('waldo'));
describe('MainController', function () {
var $scope, createController;
beforeEach(inject(function ($rootScope, $controller) {
$scope = $rootScope.$new();
createController = function (value2) {
return $controller('MainController', {
$scope: $scope,
value2: value2
});
};
}));
it('exists', function () {
var value2 = ["google", "yahoo"];
var controller = createController(value2);
expect(controller).not.toBeNull();
$scope.val = 10;
$scope.someFunction();
assert.equal($scope.val, value2.length);
});
});
});
I am getting an error like below:
TypeError: Cannot read property 'length' of undefined
at Scope.MainController.$scope.someFunction (absolute/home/guru/app/controllers/MainController.js?131fd944e9e94b3a4ee4eb524e48e17a87dd4820:43:51)
createController = function (value2) {
$scope.value2 = value2;
return $controller('MainController', {
$scope: $scope
});
};
Every Angular controller has an associated $scope object.
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.master = {};
$scope.update = function(user) {
$scope.master = angular.copy(user);
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="formExample">
<div ng-controller="ExampleController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<input type="button" ng-click="reset()" value="Reset" />
<input type="submit" ng-click="update(user)" value="Save" />
</form>
<pre>user = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
</body>
Reference:
https://docs.angularjs.org/guide/forms

How to use ng-model / $scope with Angular Factory and Controller

// SERVICES
app.factory('searchFactory', ['$http', function($http) {
return $http.post("/api", { tag: "food" });
}]);
// CONTROLLERS
app.controller('MainController', ['$scope', 'searchFactory', function ($scope, searchFactory) {
$scope.submit = function () {
searchFactory.then(function(response) {
$scope.recipeData = JSON.parse(response.data);
});
};
// HTML
<form ng-submit="submit()">
<div class="form-group">
<input type="text" ng-model="recipeTag" class="form-control" />
<input type="submit" class="btn btn-primary" value="Find Recipes" />
</div>
</form>
Does anyone know how I can use $scope.recipeTag from ng-model to replace "food" in the factory? I need to be able to pass the form input as a parameter into the factory.
you need to create a funtion that expects a parameter in your factory.
Example:
var factory= {
post: function(customTag) {
return $http.post("/api", { tag: customTag });
}
};
return factory;

Categories

Resources