Angularjs ReferenceError: function is not defined - javascript

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,

Related

angular.js building a fully custom $state.go()

I've tried to do this in many ways, ui-sref is not working for me ok because data make it undefined by the time it is created.
I'm quite new even programming but fighting a lot with angular these days.
The point is that is this possible to really create a fully custom $state.go?
When I say fully custom is, how can i construct even the key of the parameter?
In:
$state.go(stateName, {key:value}
Thanks
angular.module('app').directive('directive', ['$state', function ($state) {
function link(scope, elements, attibutes) {
//variable data coming example
data = {
name: 'name',
params: {
key: 'id',
value: 'sidvalue'
}
}
scope.back = function (data) {
$state.go(data.name, '{' + data.params.key + ':"' + data.params.value + '"}');
}
}
return {
restrict: 'E',
link: link,
templateUrl: 'path.html'
};
}]);
EDIT: *********
This is the historic factory gathering info from each state with push and getting it from with my logic when is convenient with get:
angular.module('app').factory('Historic', ['$q', '$state', function ($q, $state) {
var historic = [];
return {
historic: {
push: function (key, value) {
var str, init = 'general.home';
str = {
name: $state.current.name,
params: {
key: key,
value: value
}
};
if ($state.current.name === init) {
historic = [{
name: $state.current.name,
}];
} else if (historic.length <= 0) {
historic.push({name: init});
} else if (historic[historic.length - 1].name !== str.name && historic[historic.length - 1].params !== str.params) {
historic.push(str);
}
},
get: function () {
var h = historic[historic.length - 2];
if (historic.length === 1) {
h = historic[0];
}
return $q(function (resolve, reject) {
resolve(h);
});
},
pop: function () {
historic.pop();
},
status: function () {
return historic.length;
}
}
};
}]);
For getting it I'm using a directive with a bit more code attached.
Publishing only the related to historic part.
angular.module('app').directive('directiveName', ['$state', 'fHistoric', function ($state, fHistoric) {
function link(scope, elements, attibutes) {
/*
historic setup
*/
if (fHistoric.historic.status > 3) {
scope.home = true;
}
function keycomp(data) {
if (data.params) {
key = {id: data.params.value};
} else {
key = {};
}
}
scope.back = function () {
fHistoric.historic.get()
.then(function (data) {
keycomp(data);
if (key) {
$state.go(data.name, key);
} else {
$state.go(data.name);
}
});
fHistoric.historic.pop();
};
}
return {
restrict: 'E',
link: link,
scope: {
header: '#',
state: '#'
},
templateUrl: 'path.html'
};
}]);
I really don't like the solution proposed, it is working but the problem with the key values made me to wrap some spaguetti code I really don't like to solve the id: coming from the key value.
Open to new ideas. ;)

AngularJS RouteParams

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.

Why am I getting "Incorrect injection token!" in this angular application code?

I'm trying to setup a restful API interface via AngularJS with the following code:
'use strict';
(function(angular) {
function ApiAction($resource, ResourceParameters) {
return $resource(ResourceParameters.route,
{ },
{ api_index: {
method: ResourceParameters.method,
isArray: true
}
});
return $resource(ResourceParameters.route,
{ },
{ create: {
method: ResourceParameters.method,
isArray: true
}
}
);
}
function ResourceParameters($scope) {
var factory = {};
factory.method = '';
factory.route = '';
factory.SetMethod = function(method) {
factory.method = method;
}
factory.SetRoute = function(route) {
factory.route = route;
}
return factory;
}
function superheroCtr($scope, ApiAction, ResourceParameters) {
$scope.superheroSubmit = function() {
// ApiAction.create({}, { superhero_name: $scope.superheroName, age: $scope.superheroAge });
angular.forEach($scope.superheroes, function(hero) {
// ApiAction.create({}, { superhero_name: hero.superhero_name, age: hero.age });
});
};
var heroesResources = ResourceParameters($scope).SetRoute('/api/');
var heroes = ApiAction.api_index({}, heroesResources);
$scope.superheroes = [];
heroes.$promise.then(function(data) {
angular.forEach(data, function(item) {
$scope.superheroes.push(item);
});
}, function(data) {
//if error then...
});
$scope.appendSuperheroFields = function() {
var i = $scope.superheroes.length + 1;
$scope.superheroes.push({"id": i, age: "", superhero_name: "" })
}
}
var superheroApp = angular.module('superheroApp', ['ngResource']);
superheroApp.controller('superheroCtr', ['$scope', 'ApiAction', 'ResourceParameters', superheroCtr]);
superheroApp.factory('ResourceParameters', ['$scope', ResourceParameters]);
superheroApp.factory('ApiAction', ['$resource', ResourceParameters, ApiAction]);
})(angular);
Yet, when I run it I get the following error:
Error: [$injector:itkn] Incorrect injection token! Expected service name as string, got function ResourceParameters($scope)
Why is this?
Simply you can not inject $scope OR you can not have access to $scope
inside a factory
Your problem is at this line
superheroApp.factory('ResourceParameters', ['$scope', ResourceParameters]);
You need to replace that line with
superheroApp.factory('ResourceParameters', [ResourceParameters]);
Factory
function ResourceParameters() { //<--removed $scope from here
var factory = {};
factory.method = '';
factory.route = '';
factory.SetMethod = function(method) {
factory.method = method;
}
factory.SetRoute = function(route) {
factory.route = route;
}
return factory;
}
Update
Additionally you should correct the declaration of ApiAction where ResourceParameters should be placed inside ' single qoutes
superheroApp.factory('ApiAction', ['$resource', 'ResourceParameters', ApiAction]);

Angular controller function minification error

I have the Angular controller below. When it is run, I get the error "TypeError: t.getDealers is not a function". This is caused by the minification of the javascript. However, I'm not sure how to fix this.
myApp.controller('DLOController', ['$scope', 'DLOFactory',
function ($scope, DLOFactory) {
$scope.init = function () {
$scope.searchType = [{ id: 1, name: "Search by Postcode" }, { id: 2, name: "Search by State" }, { id: 3, name: "Search by Dealer" }];
$scope.selectedSearchType = 1;
$scope.selectedState = -1;
$scope.postcode = "";
$scope.dealerName = "";
$scope.states = [];
$scope.dealers = [];
getStates(2);
getDealers(2);
}
function getStates(categoryType) {
DLOFactory.getStates(categoryType)
.success(function (val) {
$scope.states = val;
})
.error(function (error) {
// REVISIT: LOG ERROR HERE.
});
}
function getDealers(categoryType) {
DLOFactory.getDealers(categoryType)
.success(function (val) {
$scope.dealers = val;
console.log($scope.dealers);
})
.error(function (error) {
// REVISIT: LOG ERROR HERE.
});
}
}
]);
Here is my factory:
myApp.factory('DLOFactory', ['$http', function ($http) {
var stateList = [];
var dealerList = [];
return {
getStates: function (categoryType) {
return $http({
method: 'GET',
url: '/Addresses/GetStateList',
params: { categoryType: categoryType }
})
.success(function (responseData) {
stateList.push(responseData);
});
},
getStateList: function () {
return stateList;
},
setStateList: function (sl) {
stateList = sl;
}
}
return {
getDealers: function (categoryType) {
return $http({
method: 'GET',
url: '/Websites/GetDealers',
params: { categoryType: categoryType }
})
.success(function (responseData) {
dealerList.push(responseData);
});
},
getDealerList: function () {
return dealerList;
},
setDealerList: function (dl) {
dealerList = dl;
}
}
}]);
The minified code looks like this:
myApp.controller("DLOController",["$scope","DLOFactory",function(n,t){function i(i){t.getStates(i).success(function(t){n.states=t}).error(function(){})}function r(i){t.getDealers(i).success(function(t){n.dealers=t;console.log(n.dealers)}).error(function(){})}n.init=function(){n.searchType=[{id:1,name:"Search by Postcode"},{id:2,name:"Search by State"},{id:3,name:"Search by Dealer"}];n.selectedSearchType=1;n.selectedState=-1;n.postcode="";n.dealerName="";n.states=[];n.dealers=[];i(2);r(2)}}]);
You have two returns on the factory so second return won't execute. So merge both returns & try.

angularjs restricting count to current scope

I am tring to setup a counter where for each country in my list I can keep count of how many clicks there has been plus an overall tally.
I have the below so far which can be viewd in this fiddle. The issue I am having is that I am not able to keep the count unique for each country. How can this be achieved?
<div ng-app="myApp">
<div data-ng-view></div>
</div>
'use strict';
var myApp = angular.module('myApp', ['ngRoute', 'templates/view1.html', 'templates/view2.html']);
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'templates/view1.html',
controller: 'CountryListCtrl'
})
.when('/:id', {
templateUrl: 'templates/view2.html',
controller: 'CountryCtrl'
})
}]);
myApp.factory('Countries', ['$q', function ($q) {
var countriesList = [];
// perform the ajax call (this is a mock)
var getCountriesList = function () {
// Mock return json
var contriesListMock = [
{
"id": "0",
"name": "portugal",
"abbrev": "pt"
}, {
"id": "1",
"name": "spain",
"abbrev": "esp"
}, {
"id": "2",
"name": "angola",
"abbrev": "an"
}
];
var deferred = $q.defer();
if (countriesList.length == 0) {
setTimeout(function () {
deferred.resolve(contriesListMock, 200, '');
countriesList = contriesListMock;
}, 1000);
} else {
deferred.resolve(countriesList, 200, '');
}
return deferred.promise;
}
var getCountry = function(id) {
var deferred = $q.defer();
if (countriesList.length == 0) {
getCountriesList().then(
function() {
deferred.resolve(countriesList[id], 200, '');
},
function() {
deferred.reject('failed to load countries', 400, '');
}
);
} else {
deferred.resolve(countriesList[id], 200, '');
}
return deferred.promise;
}
var cnt = 0;
var cntryCnt = 0;
var incCount = function() {
cnt++;
return cnt;
}
var incCntryCount = function(id) {
cntryCnt++;
return cntryCnt;
}
return {
getList: getCountriesList,
getCountry: getCountry,
getCount : function () {
return cnt;
},
getCntryCount : function () {
return cntryCnt;
},
incCount: incCount,
incCntryCount: incCntryCount
};
}]);
myApp.controller('CountryListCtrl', ['$scope', 'Countries', function ($scope, Countries) {
$scope.title = '';
$scope.countries = [];
$scope.status = '';
Countries.getList().then(
function (data, status, headers) { //success
$scope.countries = data;
},
function (data, status, headers) { //error
$scope.status = 'Unable to load data:';
}
);
}]);
myApp.controller('CountryCtrl', ['$scope', '$routeParams', 'Countries', function ($scope, $routeParams, Countries) {
$scope.country = {
id: '',
name: '',
abbrev: ''
};
var id = $routeParams.id;
Countries.getCountry(id).then(
function(data, status, hd) {
console.log(data);
$scope.country = data;
$scope.countOverall = Countries.getCount;
$scope.countCntry = Countries.getCntryCount;
$scope.clickCnt = function () {
$scope.countTotal = Countries.incCount();
$scope.country.clicks = Countries.incCntryCount(id);
console.log($scope);
};
},
function(data, status, hd) {
console.log(data);
}
);
}]);
angular.module('templates/view1.html', []).run(["$templateCache", function ($templateCache) {
var tpl = '<h1>{{ title }}</h1><ul><li ng-repeat="country in countries"><a href="#{{country.id}}">{{country.name}}</div></li></ul>';
$templateCache.put('templates/view1.html', tpl);
}]);
angular.module('templates/view2.html', []).run(["$templateCache", function ($templateCache) {
var tpl = '<div>{{country.name}} clicks {{countCntry()}} <br> overall clicks {{countOverall()}}</div><button>BACK</button><button ng-click="clickCnt()" >count clicks ++ </button>';
$templateCache.put('templates/view2.html', tpl);
}]);
The problem is that you are not incrementing a count based on the country. Working on the fiddle right now.
EDIT:
I've updated the fiddle: http://jsfiddle.net/1xtc0zhu/2/
What I basically did was making the cntryCnt an object literal which takes the country id as a property and keeps the right counting per each id, like so:'
var cnt = 0;
var cntryCnt = {};
...
// The function now receives the country id and increments the specific country clicks only.
var incCntryCount = function(id) {
cntryCnt[id] = cntryCnt[id] || 0;
cntryCnt[id]++;
return cntryCnt[id];
}
The rest of the changes are in the templates, and are basically only sending the country id as a param when getting or incrementing the counts.
Also, this is not an Angular Specific question, but more a programming in general question.

Categories

Resources