AngularJS factory issue - javascript

In order to make use of Angular JS I tried to use Factory for my data stack...
Now, It does not work. I have just put a simple json data to be returned by factory, and then
the script has stopped working. It is the most basic example of angularjs as it uses json to
repeat and iterate through.
Here is all angularjs that I have written:
var Item = angular.module("Item", ['ngRoute']);
Item.config(function($routeProvider){
$routeProvider
.when("/add", {
controller : "ItemController",
templateUrl : "index.html"
})
.when("/edit", {
controller : "ItemController",
templateUrl : "index.html"
});
});
Item.factory("ItemsFactory", function(){
var items = [
{ name : "Washing Powder",
price : "2000",
balance : 14
},
{ name : "Shampoo",
price : "8500",
balance : 03
},
{ name : "Soap",
price : "1850",
balance : 27
}
];
var factory = {};
factory.getItems() = function(){
return items;
};
factory.postItems() = function(){
// POST items
};
return factory;
});
Item.controller("ItemController", function($scope, ItemsFactory){
$scope.items = ItemsFactory.getItems();
init();
function init()
{
$scope.items = ItemsFactory.getItems();
}
$scope.AddNewItem = function(){
$scope.items.push({
name : $scope.NewItem.name,
price : $scope.NewItem.price
});
};
});
And here is the HTML markup:
<!DOCTYPE html>
<html >
<head>
<title>Practicing AngularJS Framework...!</title>
<script src="angular.js" type="text/javascript"></script>
<script src="ngroute.js" type="text/javascript"></script>
<script src="scripts.js" type="text/javascript"></script>
</head>
<body data-ng-app="Item">
<div data-ng-controller="ItemController">
<div data-ng-repeat="each in items">
<p>Item {{ each.name }} costs {{ each.price }}.</p>
</div>
<div>
<input type="text" data-ng-model="NewItem.name" />
<input type="text" data-ng-model="NewItem.price" />
<br />
<input type="submit" value="Add Item" data-ng-click="AddNewItem()" />
</div>
</div>
</body>
</html>
It does not load of the json content to repeat them instantly...Nothing happens..

I think it is better to use some thing like this to return value in service :
Item.factory("ItemsFactory", function(){
var items = [
{ name : "Washing Powder",
price : "2000",
balance : 14
},
{ name : "Shampoo",
price : "8500",
balance : 03
},
{ name : "Soap",
price : "1850",
balance : 27
}
];
return {
getItems: function(){
return items;
},
postItems:function(){
}
});
also it think :
factory.getItems() = function(){}
is wrong and the correct is :
factory.getItems = function(){}

Related

How do I pass array information using a factory in Javascript?

Using a factory, I want to get information from one page (text fields and a submit button), put it in an array, and read from that array to post it into a different page. Here is a snippet of my code.
app.factory("service", function(){
var serv = {};
serv.arr = [];
serv.add = (title, name, post, tag) => serv.arr.push({
"title" : title, "name" : name, "post" : post, "tag" : tag
});
return serv;
});
app.controller("createCtrl", ["$scope", "service", function($scope, service)
{
display = () => service.add($scope.title, $scope.name, $scope.post,
$scope.tag);
console.log(service.arr);
}]);
app.controller("newsCtrl", ["$scope", "service", function($scope, service){
$scope.newsPage = "News";
$scope.array = service.arr;
}]);
I know I'm probably way off but at this stage I can't even tell if any information is being added to the array.
Try below code for set & get data from factory.
Click on SAVE DATA & then GET DATA buttons to see the actions
(function(ng, app){
app = angular.module('app', [])
app.factory("service", function(){
var serv = {};
var arr = [];
return {
add : function (title, name, post, tag) {
arr.push({
"title" : title, "name" : name, "post" : post, "tag" : tag
});
},
get : function (firstname) {
return arr[0];
}
}
});
app.controller("createCtrl", ["$scope", "service", function($scope, service)
{
$scope.display = function(){
service.add($scope.title, $scope.name, $scope.post, $scope.tag);
};
}]);
app.controller("newsCtrl", ["$scope", "service", function($scope, service){
$scope.newsPage = "News";
$scope.getData = function(){
$scope.array = service.get();
};
}]);
}(angular));
input {
margin: 5px;
}
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
<div ng-controller="createCtrl as main">
<h1>create Ctrl</h1>
<input ng-model="title" placeholder="title" /><br/>
<input ng-model="name" placeholder="name" /><br/>
<input ng-model="post" placeholder="post" /><br/>
<input ng-model="tag" placeholder="tag" /><br/>
<button ng-click="display()"> SAVE DATA </button>
</div>
<br/> <hr/>
<div ng-controller="newsCtrl">
<h2>news Ctrl </h2>
<button ng-click="getData()"> GET DATA </button>
<p> title : {{array.title}} </p>
<p> name : {{array.name}} </p>
<p> post : {{array.post}} </p>
<p> tag : {{array.tag}} </p>
</div>
</body>
</html>

How to capture data in angularjs scope from autocomplete location text field

I'm working on one angularjs form which includes location text field. For location text field I'm using google maps to autocomplete. Problem is, I'm unable to store full data database using data-ng-model. Because, only entered text is getting binded and stored in database, not full data. For Example, If I type "Pun" autocomplete populates "Pune, Maharashtra, India", but only "Pun" is storing in database(because I only typed "Pun" in text field. How to capture full data and convert it into json and store it in database? Please help me with this. Thanks in advance.
Here is my code:
JavaScript
<script type="text/javascript">
var app = angular.module('formSubmit', []);
app.controller('FormSubmitController',[ '$scope', '$http', function($scope, $http) {
/* $scope.myDataBlurred = $scope.area; */
$scope.list = [];
$scope.headerText = 'AngularJS Post Form Spring MVC example: Submit below form';
$scope.blurred = function() {
$scope.myDataBlurred = $scope.area;
}
$scope.submit = function() {
var formData = {
"agreement_exp_date" : $scope.agreement_exp_date,
"amenities" : $scope.amenities,
"area": $scope.myDataBlurred,
"bathrooms" : $scope.bathrooms,
"bedrooms" : $scope.bedrooms,
"State": $scope.State,
"city": $scope.city,
"country" : $scope.country,
"current_property_status" :$scope.current_property_status,
"car_spaces" : $scope.car_spaces,
"expired" : $scope.expired,
"furnished" : $scope.furnished,
"floor_or_level" : $scope.floor_or_level,
"house_number" : $scope.house_number,
"notes" : $scope.notes,
"ofname" : $scope.ofname,
"pfname" : $scope.pfname,
"parking_type" : $scope.parking_type,
"pincode" : $scope.pincode,
"prop_avail_date" : $scope.prop_avail_date,
"prpty_owner_email_id" : $scope.prpty_owner_email_id,
"prpty_pm_email_id" : $scope.prpty_pm_email_id,
"prpty_registration_no" : $scope.prpty_registration_no,
"prpty_type" : $scope.prpty_type,
"sqft" : $scope.sqft,
"street_name" : $scope.sqft,
"verified" : $scope.verified,
"prpty_type_sub" : $scope.prpty_type_sub,
"published_on": $scope.published_on,
"profile": $scope.profile
/* "location" : $scope.location,
"phone" : $scope.phone */
};
var response = $http.post('/Owner/addprop', formData);
response.success(function(data, status, headers, config) {
$scope.list.push(data);
});
response.error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
//Empty list data after process
$scope.list = [];
$scope.$setPristine();
};
}]);
</script>
HTML
<div class="col-md-6">
<span> Location<i style="color: red;">*</i>
<div id="locationField">
<input id="autocomplete" name="property_loc"
placeholder="Search for location" onFocus="geolocate()"
type="text" class="form-control" value="${locn}" data-ng-model="area" ng-blur="blurred()" required></input>
</div>
</div>
Go for this code!
It works with the Google Maps API. Start by typing a city name in the input field!
Dont`t look at the warnings and errors. If you add an API key it works without!
var myApp = angular.module('myApp', []);
myApp.directive('googleplace', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, model) {
var options = {
types: []
};
scope.gPlace = new google.maps.places.Autocomplete(element[0], options);
google.maps.event.addListener(scope.gPlace, 'place_changed', function() {
scope.$apply(function() {
model.$setViewValue(element.val());
});
});
}
};
});
function MyCtrl($scope) {
$scope.gPlace;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div>Your location is: {{chosenPlace}}</div>
<div><input ng-model="chosenPlace" googleplace/></div>
</div>

Call Angular nested functions

I'm trying to call a nested function in Angular. I've formatted the functions in such a way in order to neaten up code, yet when invoking the function through an ng-click it doesnt seem to work.
In my case, a scope conflict occurs because the variable name is taken by the local scope, so I've named a controller and invoked it as a child property of the controller, but no success.
I've created a jsfiddle to demonstrate what I mean:
https://jsfiddle.net/838L40hf/16/
HTML:
<div class="InviteAppContainer" ng-app="InviteApp">
<div ng-controller="InviteController as cntrl">
<button ng-click="alert()">
Alert, standard
</button>
<div ng-repeat="invite in invites">
<button ng-click="cntrl.invite.alert(invite.name)">
Alert, {{invite.name}}
</button>
</div>
</div>
</div>
JS:
var InviteApp = angular.module('InviteApp',[])
.controller('InviteController', function($scope) {
$scope.invites = {
0 : {
"name":"invite 1",
},
1 :{
"name" : "invite 2"
}
};
$scope.invite = {
alert : function(name) {
alert(name);
}
};
$scope.alert = function() {
alert("alert2!");
};
});
If you're using the controller as syntax, you should be binding things to this instead of $scope if you wish to access them through the aliased controller name.
Simply changing the binding from $scope.invite to this.invite will do the trick.
https://jsfiddle.net/pL4wc10n/
You should use this
Javascript
var InviteApp = angular.module('InviteApp',[])
.controller('InviteController', function($scope) {
// controllerAs : cntrl
var that = this;
$scope.invites = {
0 : {
"name":"invite 1",
},
1 :{
"name" : "invite 2"
}
};
// USING THIS you have cntrl.function
that.invite = {
alert : function(name) {
alert(name);
}
};
$scope.alert = function() {
alert("alert2!");
};
});
var InviteApp = angular.module('InviteApp',[])
.controller('InviteController', function($scope) {
$scope.invites = {
0 : {
"name":"invite 1",
},
1 :{
"name" : "invite 2"
}
};
$scope.invite = {
alert : function(name) {
alert(name);
}
};
$scope.alert = function() {
alert("alert2!");
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="InviteAppContainer" ng-app="InviteApp">
<div ng-controller="InviteController as cntrl">
<button ng-click="alert()">
Alert, standard
</button>
<div ng-repeat="i in invites">
<button ng-click="invite.alert(i.name)">
Alert, {{i.name}}
</button>
</div>
</div>
</div>
What I edit:
<div ng-repeat="i in invites">
<button ng-click="invite.alert(i.name)">
Alert, {{i.name}}
</button>
</div>

MEAN Stack Get Username from UserId forEach row

I'm trying to get the user data (such as username) for each user on a row of reviews. I kept my user information (login credentials on another model/controller), so is there a way to access and show the username on the view?
Below is my JSON code:
{
"_id": "56873fc9182b3741059357d0",
"longitude": 113.83507800000007,
"latitude": 22.1533884,
"location": "Hong Kong",
"name": "Hong Kong",
"__v": 0,
"category": "Attraction",
"reviews": [
{
"comment": "Add the comment to the form",
"rating": 3.5,
"userId": 11,
"review_id": "44NL7kkwhy72"
},
{
"comment": "Hello test",
"rating": "3.4",
"userId": "56809c0cf0a264b101a1dd61",
"review_id": "jN7f1iFlQVha"
},
{
"comment": "Hello test ty",
"rating": "3.7",
"userId": "56863c8f2959b4c601fbd9eb",
"review_id": "QcJpw4yopF1q"
}
]
},
//view all reviews for a location
.controller('AllReviews', function($scope, $stateParams, LocFac, UserFac) {
id = $stateParams.id;
LocFac.getLocation(id).then(function(data) {
$scope.locations = data.data;
$scope.reviews = data.data.reviews;
//variables to show information on location reviews
$scope.lengthrev = (data.data.reviews).length;
$scope.locationname = data.data.name;
//addition of values and retrieve the value
$scope.getTotal = function(){
var total = 0;
for(var i = 0; i < $scope.lengthrev; i++){
var review = $scope.reviews[i];
User.getUser(review).then(function(datat) {
$scope.locun = datat.username;
});
total += review.rating;
}
return total;
}
grandtotal = $scope.getTotal();
//get average of all values \
$scope.averagereviews = grandtotal/($scope.lengthrev);
});
})
My location reviews view
<ion-view view-title="All Reviews" class="all_reviews">
<ion-content class="all_reviews">
<h3>{{ locationname }}</h3>
<h3>Average Rating: {{ averagereviews }} <ng-rate-it name="rating" ng-model="averagereviews" resetable="false" read-only="true"></ng-rate-it>/ {{ lengthrev }} Reviews </h3>
<ion-list>
<ion-item data-ng-repeat="location in locations.reviews">
<ng-rate-it name="rating" ng-model="location.rating" resetable="false" read-only="true"></ng-rate-it>
{{ location.userId }}
<h4>{{ location.review_id }}</h4>
<h4>{{ location.comment }}</h4>
</ion-item>
</ion-list>
Considering your two aysnc operations,(one to fetch reviews and another one to fetch usernames) I think this approach will be more suitable.
First fetch the reviews.
Display the reviews.
While displaying the reviews use the UserFac to fetch the username asynchronously using ng-init directive.
I have created a demo plunker as an example with the sample data you provided in question.
Example:
Demo Plunker
app.js
var app = angular.module("app", []);
app.factory('LocFac', function($http) {
var factory = {};
factory.getLocation = function(id) {
return $http({
method: 'GET',
url: 'data.json'
});
}
return factory;
});
app.factory('UserFac', function($http) {
var factory = {};
factory.getUser = function(id) {
return $http({
method: 'GET',
url: 'user.json'
});
}
return factory;
});
app.controller('AllReviews', function($scope, LocFac, UserFac) {
$scope.show = false;
$scope.testClick = function() {
id = "56873fc9182b3741059357d0";
LocFac.getLocation(id).then(function(data) {
$scope.reviews = data.data.reviews;
$scope.lengthrev = (data.data.reviews).length;
$scope.show = true;
});
}
$scope.getUserName=function(review) {
UserFac.getUser(review.id).then(function(user) {
review.userName=user.data.userName;
review.showUserName=true;
});
}
})
HTML:
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.4.8" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="app" ng-controller="AllReviews">
<button ng-click="testClick()">Click here</button>
<ul ng-show="show" ng-repeat="review in reviews track by $index" ng-init="getUserName(review)">
{{review | json : spacing}}
<p ng-show="review.showUserName">
{{review.userName}}
</p>
</ul>
</body>
</html>
Explanation:
While iterating the review array in ng-repeat,we pass the review object to the UserFac service to fetch the userName.This service will set the name inside the review object itself.

AngularJS Error: Unknown provider

I'm getting the classic the classic Error: Unknown provider: UserModelProvider <- UserModel with angular JS. My code looks like this:
var ClabborApp = angular.module('clabbor', []);
ClabborApp.factory('UserModel', function() {
var UserModel = {};
var list = [];
UserModel.getItem = function(index) {
return list[index];
}
UserModel.addItem = function(item) {
list.push(item);
}
UserModel.removeItem = function(item) {
list.splice(list.indexOf(item), 1)
}
UserModel.size = function() {
return list.length;
}
return UserModel;
});
function FollowersCtrl($scope, UserModel) {
$scope.followers = [{
text : 'learn angular',
done : true,
'name' : 'James'
}, {
text : 'build an angular app',
done : false,
'name' : 'John'
}];
}
And my html looks like this:
<html lang="en" ng-app>
<meta charset="utf-8">
<body ng-app="clabbor">
<div class="content follow" ng-controller="FollowersCtrl">
<ul class="clearfix">
<!-- Show max 12 followers -->
<li ng-repeat="follower in followers">
{{follower.name}}
</li>
</ul>
</div>
</body>
</html>
I thought I did it by the book but I am getting the error. Does anyone know what could it be?
Remove the ng-app attribute from the html tag. Here's Jsfiddle that's working: http://jsfiddle.net/eA2xx/. You can't have more than one ng-app.

Categories