i am getting ReferenceError: findId is not defined this the code
var app = angular.module('sample', ['ngRoute', 'ngStorage']);
app.config(function($routeProvider) {
$routeProvider
.when('/noteTemp', {
templateUrl: 'noteTemp.html',
controller: 'MainCtrl'
})
.when('/newNote', {
templateUrl: 'newNote.html',
controller: 'MainCtrl'
})
.when('/newNote/edit/:id', {
templateUrl: 'newNote.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/noteTemp'
});
});
app.factory('StorageService', function ($localStorage) {
$localStorage = $localStorage.$default({
things: [ { id: 1, time: 'Oct 17, 2020 9:34:41 AM', message: '#hello world' },
{ id: 2, time: 'Oct 17, 2020 9:34:41 AM', message: 'COMPLETE THE IP PROJECT' },
{ id: 3, time: 'Oct 17, 2020 9:35:45 AM', message: '#hello world3' }]
});
var _getAll = function () {
return $localStorage.things;
};
var _add = function (thing) {
var updatedItem = findId(thing.id);
if (updatedItem) {
updatedItem.date = thing.date;
updatedItem.message = thing.message;
} else if(thing.message===""){
} else {
thing.id = newId();
$localStorage.things.push(thing);
}
}
var _remove = function (thing) {
$localStorage.things.splice($localStorage.things.indexOf(thing), 1);
}
return {
getAll: _getAll,
add: _add,
remove: _remove,
findId: function(id) {
for (var item in $localStorage.things) {
if ($localStorage.things[item].id === id) {
return $localStorage.things[item];
}
}
},
newId: function() {
if (NewId) {
NewId++;
return NewId;
} else {
var maxId = _.max($localStorage.things, function(thing) {
return thing.id;
});
NewId = maxId.id + 1;
return NewId;
}
}
};
});
app.controller('MainCtrl', function ($scope, $routeParams, StorageService, $location) {
$scope.things = StorageService.getAll();
if (!$routeParams.id) {
$scope.newContent = { id: 0, time: new Date(), message: '' };
} else {
$scope.newContent = _.clone(noteService.findId(parseInt($routeParams.id)));
}
$scope.add = function () {
StorageService.add($scope.newContent);
$location.path('/noteTemp');
};
$scope.remove = function (thing) {
StorageService.remove(thing);
$location.path('/noteTemp');
};
});
i think the error is i cant call a functions within the factory,
also i wanted to ask whether should i use service instead of factory.....
this is all the details i have please accept the question .
.why am i not able to post this question is my important doubt...please acccept.....
If the calling context is reliable, you can refer to this to get the returned object, and from that, get to the findId property on the returned object:
var _add = function (thing) {
var updatedItem = this.findId(thing.id);
If the calling context isn't reliable, define findId as a standalone function beforehand:
function findId(id) {
for (var item in $localStorage.things) {
if ($localStorage.things[item].id === id) {
return $localStorage.things[item];
}
}
}
// ...
return {
getAll: _getAll,
add: _add,
remove: _remove,
findId: findId,
I had a Problem in linking pages. Suppose, After Login from URL "/admin_1_angularjs/login.html",
the dashboard.html page should be Appear from this URL "/admin_1_angularjs/#/dashboard.html". instead it appeared in "/admin_1_angularjs/#/login.html" link. How do i fix this? here is my angularJS Controller...
MetronicApp.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
// Redirect any unmatched url
$urlRouterProvider.otherwise("/login.html");
app.version = '1454574448';
$stateProvider.state('login', {
url: "/login.html",
templateUrl: 'login.html?_=' + app.version,
controller: 'login'
})
.state('dashboard', {
url:"/dashboard.html",
templateUrl: 'views/profile/dashboard.html?_=' + app.version,
controller: 'dashboard'
})
this is my login controller.
var app = angular.module('myApp', []);
app.controller('login', ['$window','$scope','$timeout', function ($window,$scope,$timeout) {
$scope.hasError = false;
$scope.errorMessage = "";
$scope.input = {
username: '',
password: ''
};
$scope.counter = 0;
$scope.isLoading = false;
$scope.setError = function (hasError) {
$scope.hasError = hasError;
};
$scope.login = function () {
$scope.isLoading = true;
var postData = {
clazz: "com.smk.aps.server.model.rpc.request.RPCAdminLogin",
signature: "",
data: {
// requestLoginID: app.uuid.v4(),
// requestUsername: $scope.input.username,
// requestPassword: CryptoJS.SHA1($scope.input.password).toString()
}
};
postData.data._class = postData.clazz;
$timeout(function (data,status) {
$scope.isLoading = false;
if ($scope.hasError = true) {
if($scope.counter == 0) {
$scope.errorMessage = "Invalid username or password. Error code = " + $scope.counter;
console.log($scope.errorMessage);
$scope.counter++;
} else if ($scope.counter == 1) {
$scope.errorMessage = "Server busy please try again later. Error code = " + $scope.counter;
console.log($scope.errorMessage);
$scope.counter++;
} else {
$window.location.href = "/admin_1_angularjs/";
}
}
}, 2000);
You have to set HTML5 mode to true to get desired result. Please refer to HTML5Mode section of following link for more details.
https://docs.angularjs.org/guide/$location
I dont understand why but when i console.log() both box and box.color its telling me its undefined...I tried many different methods to solve this problem but it all failed.
Cloud9
Plunker
And here is script.js:
var app = angular.module('LoginApp', ["firebase", "ngRoute", "ngCookies"])
app.provider("box", function ()
{
var hex = "SomeColor";
var UID = 3;
return {
setColor: function (value)
{
UID = value
},
$get: function ()
{
return {
color: hex
}
}
}
})
app.config(function ($routeProvider, $cookiesProvider) {
$routeProvider
.when('/', {
templateUrl: 'HtmlFiles/registration.html',
controller: 'regController'
})
.when('/logIn', {
templateUrl: 'HtmlFiles/login.html',
controller: 'loginController'
})
.when('/Chat', {
templateUrl: 'HtmlFiles/Chat.html',
controller: 'chatController'
})
.when('/Test' , {
template: '<h3>This is just a testing phase</h3>',
controller: 'Testing'
})
.when('/userSettings', {
templateUrl: 'HtmlFiles/userSettings.html',
controller: 'userSettingsController'
})
.when('/room', {
templateUrl: 'HtmlFiles/room.html',
controller: 'roomController'
})
.otherwise({
redirectTo: '/'
});
});
app.controller('Testing', ["$scope","roomService", "roomProvider", function($scope, roomService, roomProvider){
console.log("This is from the Controller Service: " + roomService.room.roomUID)
console.log("This is from the Controller Provider: " + roomProvider.$get)
}
])
app.factory("Auth", ["$firebaseAuth",
function($firebaseAuth) {
var ref = new Firebase("https://chattappp.firebaseio.com/");
return $firebaseAuth(ref);
}
]);
app.factory("Ref", function(){
var ref = new Firebase("https://chattappp.firebaseio.com/")
return ref;
})
app.factory("UniPosts" , function(){
var ref = new Firebase("https://postss.firebaseio.com/")
return ref;
});
app.service('getCookieService', ["$cookieStore", "$scope",
function($cookieStore, $scope){
this.getCookie = function(name){
$cookieStore.get(name)
}
}
])
roomController.js:
app.controller('roomController', ["$scope", "Auth", "Ref", "AuthService", "roomService","$http",
function($scope, Auth, Ref, AuthService, roomService, $http,box) {
// Sweet Alert :)
function generateRandomStringToken(length) {
var string = "";
var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < length; i++){
string += characters.charAt(Math.floor(Math.random() * characters.length));
}
return string;
}
swal({
title: "Room",
text: "What do you want your room name to be?",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "Write something"
}, function(inputValue) {
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("You need to write something!");
return false
}
swal("Nice!", "You wrote: " + inputValue, "success");
$scope.$apply(function () {
$scope.roomNameModel = inputValue
});
console.log($scope.roomNameModel)
var redirectPage = generateRandomStringToken(10)
console.log("User gets redirected to : " + redirectPage + " ...")
roomService.setRoomUID(redirectPage);
console.log(roomService.room.roomUID)
console.log(box) //Undefined...
console.log("From Provider : " + box.color)//box.color is undefined..
});
}
])
//window.location.hash = "/Test"
EDIT 2: Ok Now it works but im confused on how to use it on app.config.. i My provider is Hash:
app.provider("Hash", function ()
{
var UID = 0;
return {
$get: function ()
{
return {
setHash: function (value)
{
UID = value;
},
getHash: function()
{
return UID;
}
}
}
}
})
And when it goes to the controller i set the hash and get the has ... roomControler.js:
app.controller('roomController', ["$scope", "Auth", "Ref", "AuthService", "roomService","$http", "Hash",
function($scope, Auth, Ref, AuthService, roomService, $http,Hash) {
// Sweet Alert :)
function generateRandomStringToken(length) {
var string = "";
var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < length; i++){
string += characters.charAt(Math.floor(Math.random() * characters.length));
}
return string;
}
swal({
title: "Room",
text: "What do you want your room name to be?",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "Write something"
}, function(inputValue) {
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("You need to write something!");
return false
}
swal("Nice!", "You wrote: " + inputValue, "success");
$scope.$apply(function () {
$scope.roomNameModel = inputValue
});
console.log($scope.roomNameModel)
var redirectPage = generateRandomStringToken(10)
console.log("User gets redirected to : " + redirectPage + " ...")
roomService.setRoomUID(redirectPage);
console.log(roomService.room.roomUID);
Hash.setHash(redirectPage);
console.log("From Provider : " + Hash.getHash())
window.location.hash = "/Test"
});
}
])
Now what i want to do is in my app.config() i want to say when it is in Hash.getHash() Go to template: , and controller:
So something like this....
app.config(function ($routeProvider, $cookiesProvider, Hash) {
$routeProvider.
when('/' + Hash.getHash(), {
template: '<h4> Your in Room',
controller: 'Test
})
});
app.controller('Testing', ["$scope","roomService","Hash",function($scope, roomService, Hash){
console.log("This is from the Controller Service: " + roomService.room.roomUID)
console.log(Hash.getHash())//This Logs right. :D
}
])
EDIT 3
What i was trying to say earlier was that i want to somehow configure the randomly generated Hash in my app.config() when statements. so in my app.config. WHEN the USER is in /RANDOMLYGENERATEDHASH have a template: '<h1>Test</h1>' . This is what i tried but dosent workk...
It is the fourth one on the .when() Statements..
app.config(function ($routeProvider, $cookiesProvider, HashProvider){
$routeProvider
.when('/', {
templateUrl: 'HtmlFiles/registration.html',
controller: 'regController'
})
.when('/logIn', {
templateUrl: 'HtmlFiles/login.html',
controller: 'loginController'
})
.when('/Chat', {
templateUrl: 'HtmlFiles/Chat.html',
controller: 'chatController'
})
.when('/' + HashProvider , {
templete: '<h1>Test</h1>'
})
.when('/userSettings', {
templateUrl: 'HtmlFiles/userSettings.html',
controller: 'userSettingsController'
})
.when('/room', {
templateUrl: 'HtmlFiles/room.html',
controller: 'roomController'
})
.otherwise({
redirectTo: '/'
});
});
And here is the provider now..
app.provider("Hash", function ()
{
var UID = 0;
var _getHash = function()
{
return UID;
};
return {
getHash: _getHash,
$get: function ()
{
return {
setHash: function (value)
{
UID = value;
},
getHash: _getHash
}
}
}
})
EDIT 4
Ok This is my roomcontroller.js Now..:
(Important detail at bottom of controller)
app.controller('roomController', ["$scope", "Auth", "Ref", "AuthService", "roomService","$http", "Hash","$routeParams",
function($scope, Auth, Ref, AuthService, roomService, $http,Hash, $routeParams) {
// Sweet Alert :)
function generateRandomStringToken(length) {
var string = "";
var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < length; i++){
string += characters.charAt(Math.floor(Math.random() * characters.length));
}
return string;
}
swal({
title: "Room",
text: "What do you want your room name to be?",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "Write something"
}, function(inputValue) {
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("You need to write something!");
return false
}
swal("Nice!", "You wrote: " + inputValue, "success");
$scope.$apply(function () {
$scope.roomNameModel = inputValue
});
console.log($scope.roomNameModel)
var redirectPage = generateRandomStringToken(10)
console.log("User gets redirected to : " + redirectPage + " ...")
roomService.setRoomUID(redirectPage);
console.log(roomService.room.roomUID);
Hash.setHash(redirectPage);
console.log("From Provider : " + Hash.getHash())
$routeParams.hash = Hash.getHash()
});
}
])
and script.js(Note this is not the only ones i have. You can see all other on above link on Cloud9(Plunk not updated)):
var app = angular.module('LoginApp', ["firebase", "ngRoute", "ngCookies", 'ngMessages'])
app.provider("Hash", function ()
{
var UID = 0;
var _getHash = function()
{
return UID;
};
return {
getHash: _getHash,
$get: function ()
{
return {
setHash: function (value)
{
UID = value;
},
getHash: _getHash
}
}
}
})
app.config(function ($routeProvider, $cookiesProvider, HashProvider){
$routeProvider
.when('/', {
templateUrl: 'HtmlFiles/registration.html',
controller: 'regController'
})
.when('/logIn', {
templateUrl: 'HtmlFiles/login.html',
controller: 'loginController'
})
.when('/Chat', {
templateUrl: 'HtmlFiles/Chat.html',
controller: 'chatController'
})
.when('/:Hash', {
template: '<h1>TEST TEST</h1>',
controller: 'any controller'
})
.when('/userSettings', {
templateUrl: 'HtmlFiles/userSettings.html',
controller: 'userSettingsController'
})
.when('/room', {
templateUrl: 'HtmlFiles/room.html',
controller: 'roomController'
})
.otherwise({
redirectTo: '/'
});
});
app.controller('Testing', ["$scope","roomService","Hash",function($scope, roomService, Hash){
console.log("This is from the Controller Service: " + roomService.room.roomUID)
console.log(Hash.getHash())
}
])
app.factory("Auth", ["$firebaseAuth",
function($firebaseAuth) {
var ref = new Firebase("https://chattappp.firebaseio.com/");
return $firebaseAuth(ref);
}
]);
app.factory("Ref", function(){
var ref = new Firebase("https://chattappp.firebaseio.com/")
return ref;
})
app.factory("UniPosts" , function(){
var ref = new Firebase("https://postss.firebaseio.com/")
return ref;
});
app.service('getCookieService', ["$cookieStore", "$scope",
function($cookieStore, $scope){
this.getCookie = function(name){
$cookieStore.get(name)
}
}
])
[1]: https://ide.c9.io/amanuel2/chattapp
[2]: https://plnkr.co/edit/ToWpQCw6GaKYkUegFjMi?p=preview
There are two problems in your code:
Definition of "roomController"
app.controller('roomController', ["$scope", "Auth", "Ref",
"AuthService", "roomService","$http",
function($scope, Auth, Ref, AuthService, roomService,
$http,box) {})
Just match the parameters and their declarations and you will see that you missed a declaration for the "box" parameter. The correct "roomController" definition should be like this:
app.controller('roomController', ["$scope", "Auth", "Ref", "AuthService", "roomService","$http", "box",
function($scope, Auth, Ref, AuthService, roomService, $http,box)
"box" provider. You defined "setColor" method as the configuration method of provider, but you are trying to use it as a provider result method. The corrected version should be like this:
app.provider("box", function ()
{
var hex = "SomeColor";
var UID = 3;
return {
$get: function ()
{
return {
color: hex,
setColor: function (value)
{
UID = value
}
}
}
}
})
Angular Providers
Answer to EDIT2:
You defined HashProvider. To configure it in app.config you should pass argument as HashProvider (not just Hash, BUT when you will try to use it anywhere except app.config you should inject it as Hash). So your app.config declaration should be like this:
app.config(function ($routeProvider, $cookiesProvider, HashProvider)
...and to let you access the getHash method it's necessary to move it to the provider configuration, for example like this:
app.provider("Hash", function ()
{
var UID = 0;
var _getHash = function()
{
return UID;
};
return {
getHash: _getHash,
$get: function ()
{
return {
setHash: function (value)
{
UID = value;
},
getHash: _getHash
}
}
}
})
Answer to EDIT3:
Now I got what you are trying to do. And the thing is that you are trying to do it wrong :). The right way is more simple. You have to configure route with param, for example like this:
.when('/:hash', {
template: '<h1>TEST TEST</h1>',
controller: 'any controller'
})
And place it just after your last route. After that, in controller you may access hash by using $routeParams object. For example like this:
$routeParams.hash
And after that in controller you may analyze if it's right hash and do necessary stuff, or redirect user somewhere if hash is invalid.
I am working with wordpress' rest api and I am extracting a list of posts which allow the user to see a single post. Now I want to include the comments as well but I cannot wrap my head around this. I am using a factory for the calls:
.factory('Articles', function ($http) {
var articles = [];
storageKey = "articles";
function _getCache() {
var cache = localStorage.getItem(storageKey );
if (cache)
articles = angular.fromJson(cache);
}
return {
all: function () {
return $http.get("http://www.examplesite.com/tna_wp/wp-json/posts?filter[category_name]=test").then(function (response) {
articles = response.data;
console.log(response.data);
return articles;
});
},
get: function (articleId) {
if (!articles.length)
_getCache();
for (var i = 0; i < articles.length; i++) {
if (parseInt(articles[i].ID) === parseInt(articleId)) {
return articles[i];
}
}
return null;
}
}
})
My controller:
.controller('ExampleCtrl', function ($scope, $stateParams, _, Articles) {
$scope.articles = [];
Articles.all().then(function (response){
$scope.articles = response;
window.localStorage.setItem("articles", JSON.stringify(response));
},
function (err) {
if(window.localStorage.getItem("articles") !== undefined) {
$scope.articles = JSON.parse(window.localStorage.getItem("articles"));
}
}
);
$scope.doRefresh = function() {
Articles.all().then(function (articles){
var loadedIds = _.pluck($scope.articles, 'id');
var newItems = _.reject(articles, function (item){
return _.contains(loadedIds, item.id);
});
$scope.articles = newItems.concat($scope.articles);
$scope.$broadcast('scroll.refreshComplete');
});
};
})
//THIS IS WHERE I AM TRYING AND FAILING
.controller('ExampleInnerCtrl', function ($http, $scope, $stateParams, $cordovaSocialSharing, $ionicModal, Articles) {
$scope.article = Articles.get($stateParams.articleId);
var url = Articles.get($stateParams.articleId);
$scope.comments = [];
$http.get("http://www.example.com/tna_wp/wp-json/posts/" +url+ "/comments").then(function (response, commentId) {
$scope.comments = response.data;
console.log(response.data);
return $scope.comments;
});
$scope.comment = $stateParams.commentId;
$ionicModal.fromTemplateUrl('gauteng-comments.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal
})
$scope.openModal = function() {
$scope.modal.show()
}
$scope.closeModal = function() {
$scope.modal.hide();
};
$scope.$on('$destroy', function() {
$scope.modal.remove();
});
$scope.sharePost = function(link){
window.plugins.socialsharing.share('I just read this article on The New engage: ', null, null, "http://example.com" + link);
};
})
now in the controller if I include the post id manually I can get the comments for that post, however I cannot seem to store that post ID in a variable to use
--------EDIT
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: "NavCtrl"
})
.state('app.home', {
url: "/home",
views: {
'menuContent': {
templateUrl: "templates/home.html"
}
}
})
.state('app.provinces', {
url: "/provinces",
views: {
'menuContent': {
templateUrl: "templates/provinces.html"
}
}
})
.state('app.example', {
url: "/provinces/example",
views: {
'menuContent': {
templateUrl: "templates/example.html",
controller: "ExampleCtrl"
}
}
})
.state('app.exampleSingle', {
url: "/provinces/example/:articleId",
views: {
'menuContent': {
templateUrl: "templates/exampleSingle.html",
controller: "ExampleInnerCtrl"
}
}
})
;
$urlRouterProvider.otherwise("/app/home");
});
Ok it was my stupidity... I just stored the variable as: var url = $scope.article.ID;
I'm having problems creating a variable and using it in a MEAN package. I'm basing it off of the "articles" package that comes as an example. Everything I see is the same in the client-side controller, but I'm not sure why I'm catching the error when I try to start my app (with grunt) on the "books" package but not the "articles" package.
I have not implemented all the controllers that articles has yet, that may be an issue?
When I start the app with grunt, I get this error on : 'book' is defined but never used MEAN stack controller
I believe the error is in the controller, but if you need to see other files please let me know.
books.js
//client-side controller
'use strict';
angular.module('mean.books').controller('BooksController', ['$scope', 'Global', 'Books',
function($scope, Global, Books) {
$scope.global = Global;
$scope.package = {
name: 'books'
};
$scope.hasAuthorization = function(book) {
if (!book || !book.user) return false;
return $scope.global.isAdmin || book.user._id === $scope.global.user._id;
};
$scope.create = function(isValid) {
if (isValid) {
var book = new Books({
title: this.title,
author: this.author,
description: this.description,
seller: this.seller
});
/* Not sure if we need this location thing
book.$save(function(response) {
$location.path('books/' + response._id);
});
*/
this.title = '';
this.content = '';
this.description = '';
this.seller = ''; // or this.user implement
} else {
$scope.submitted = true;
}
};
}
]);
articles.js //this is the example that I'm basing it from
'use strict';
angular.module('mean.articles').controller('ArticlesController', ['$scope', '$stateParams', '$location', 'Global', 'Articles',
function($scope, $stateParams, $location, Global, Articles) {
$scope.global = Global;
$scope.hasAuthorization = function(article) {
if (!article || !article.user) return false;
return $scope.global.isAdmin || article.user._id === $scope.global.user._id;
};
$scope.create = function(isValid) {
if (isValid) {
var article = new Articles({
title: this.title,
content: this.content
});
article.$save(function(response) {
$location.path('articles/' + response._id);
});
this.title = '';
this.content = '';
} else {
$scope.submitted = true;
}
};
$scope.remove = function(article) {
if (article) {
article.$remove(function(response) {
for (var i in $scope.articles) {
if ($scope.articles[i] === article) {
$scope.articles.splice(i, 1);
}
}
$location.path('articles');
});
} else {
$scope.article.$remove(function(response) {
$location.path('articles');
});
}
};
$scope.update = function(isValid) {
if (isValid) {
var article = $scope.article;
if (!article.updated) {
article.updated = [];
}
article.updated.push(new Date().getTime());
article.$update(function() {
$location.path('articles/' + article._id);
});
} else {
$scope.submitted = true;
}
};
$scope.find = function() {
Articles.query(function(articles) {
$scope.articles = articles;
});
};
$scope.findOne = function() {
Articles.get({
articleId: $stateParams.articleId
}, function(article) {
$scope.article = article;
});
};
}
]);
In $scope.create function you defined book
var book = new Books({
and never use it. That's reason you get warning. If you want to skip jshint warnings in development use grunt -f or allow unused variables in your grunt configuration (or .jshintrc if you use it)