AngularJS variable not showing in html - javascript

Structure
statsController.js
(function (module) {
'use strict';
var statsController = function ($scope, $rootScope, $timeout, $routeParams, $location, $window, statsService) {
$scope.$on('$viewContentLoaded', function (event) {
$window.ga('send', 'pageview', { page: $location.url() });
});
var model = {};
model.stats = {};
statsService.getStats().then(function (d) {
model.stats = d;
});
};
module.controller("statsController", statsController);
}(angular.module("app")));
statsService.js
(function (app) {
var statsService = function (webapi) {
var model = {};
model.getStats = function () {
return webapi.get('stats/getstats');
}
return model;
};
app.factory("statsService", statsService);
statsService.$inject = ['webapi'];
}(angular.module("app")))
stats.html
Total paid customers: {{statsController.model.totalPaidCustomers}}<br/>
Stripe confirmed customers: {{statsController.model.stripeConfirmedCustomers}}<br />
Result from API:
{"totalPaidCustomers":1,"stripeConfirmedCustomers":2}
When I put alert() in statsController.js for d.totalPaidCustomers I get value 1, same for other parameter.
So only problem is to show this in html.
App.js
.when('/stats', {
templateUrl: 'tpl/admin/stats.html',
controller: 'statsController',
controllerAs: 'stats'
}).

If i understand correctly. It should be "model.stats"
Total paid customers: {{statsController.model.totalPaidCustomers}}
http://jsfiddle.net/f5hb9spz/8/

Try changing your state definition to this:
.when('/stats', {
templateUrl: 'tpl/admin/stats.html',
controller: 'statsController',
controllerAs: 'vm'
}).
Then change the controller to this:
(function (module) {
'use strict';
var statsController = function ($scope, $rootScope, $timeout, $routeParams, $location, $window, statsService) {
$scope.$on('$viewContentLoaded', function (event) {
$window.ga('send', 'pageview', { page: $location.url() });
});
var vm = this;
vm.model = {};
vm.model.stats = {};
statsService.getStats().then(function (d) {
vm.model.stats = d;
});
};
module.controller("statsController", statsController);
}(angular.module("app")));
Finally your view goes to this:
Total paid customers: {{vm.model.stats.totalPaidCustomers}}<br/>
Stripe confirmed customers: {{vm.model.stats.stripeConfirmedCustomers}}<br />
If you don't see anything then just put this in the view and see what you have:
{{ vm | json }}

Problem was I didn't assign the current scope to a model.
var model = this;
statsController.js
(function (module) {
'use strict';
var statsController = function ($scope, $rootScope, $timeout, $routeParams, $location, $window, statsService) {
$scope.$on('$viewContentLoaded', function (event) {
$window.ga('send', 'pageview', { page: $location.url() });
});
var model = this;
model.stats = {};
statsService.getStats().then(function (d) {
model.stats = d;
});
};
module.controller("statsController", statsController);
}(angular.module("app")));
Then call in html:
Total paid customers: {{stats.stats.totalPaidCustomers}}<br/>
Stripe confirmed customers: {{stats.stats.stripeConfirmedCustomers}}<br />
have to change name of var though(stats.stats), confused the hell out of me.

Related

How to call $resource custom method in controller

I have a factory:
myService:
'use strict';
app.factory('myService', ['$resource', 'ngAuthSettings', function ($resource, ngAuthSettings) {
var serviceBase = ngAuthSettings.apiServiceBaseUri;
return $resource(serviceBase + 'api/category/', {}, {
update: {
method: 'PUT'
},
getAllByCategory: {
url: serviceBase + 'api/category/GetAllByCategory',
method: 'GET', isArray: true
}
});
}]);
Then I have a controller:
searchController:
'use strict';
app.controller('searchController',
['ngAuthSettings', '$scope', 'myService', '$routeParams', '$location',
function (ngAuthSettings, $scope, myService, $routeParams, $location) {
function init() {
var search = $location.search();
var keywords = search.keywords;
var model = myService.getAllByCategory({ categoryId: 2, page: $routeParams.page });
$scope.categoryAds = model.ads;
$scope.bigTotalItems = model.totalCount;
$scope.maxSize = ngAuthSettings.maxPagingSize;
}
init();
}]);
Why my model.ads is always undefined? Isn't this the right way to call $resource custom method in controller?
As response may take some time but you are adding assignment very immediatly hence it happening put it in promise/action after resource,
'use strict';
app.controller('searchController', ['ngAuthSettings', '$scope', 'myService', '$routeParams', '$location',
function (ngAuthSettings, $scope, myService, $routeParams, $location) {
function init() {
var search = $location.search();
var keywords = search.keywords;
var model = myService.getAllByCategory({ categoryId: 2, page: $routeParams.page },
function() {
$scope.categoryAds = model.ads;
$scope.bigTotalItems = model.totalCount;
$scope.maxSize = ngAuthSettings.maxPagingSize;
}
);
}
init();
}
]);

Destroying AngularJS $Http.Get Cache

I can't figure out how to destroy my cache to get a new list from my server.
When I get the first list, it's work perfect, but after inserting informations to my database and sending another get to my server, the browser only show the cached version of my list, without the new data.
I tried to use cacheFactory like this:
$cacheFactory.get('$http').removeAll();
but it doesn't worked.
Here is my angular Module, Service and Controller.
Module myApp
var app = angular.module('myApp', ['ngRoute', 'LocalStorageModule', 'angular-loading-bar', 'smart-table']);
app.config(function ($routeProvider) {
$routeProvider.when("/home", {
controller: "homeController",
templateUrl: "/web/views/home.html"
});
$routeProvider.when("/cidades", {
controller: "cidadesController",
templateUrl: "/web/views/basico/cidades/cidades.html"
});
$routeProvider.otherwise({ redirectTo: "/home" });
});
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptorService');
});
app.run(['authService', function (authService) {
authService.fillAuthData();
}]);
cidadesService
'use strict';
app.factory('cidadesService', ['$http', '$cacheFactory', function ($http, $cacheFactory) {
var serviceBase = 'http://localhost:22207/';
var serviceFactory = {};
var _getCidades = function () {
$cacheFactory.get('$http').removeAll(); //This doesn't worked
return $http.get(serviceBase + 'api/cidades/getall').then(function (results) {
return results;
});
};
serviceFactory.getCidades = _getCidades;
return serviceFactory;
}]);
cidadesController
'use strict';
app.controller('cidadesController', ['$scope', 'cidadesService', function ($scope, service) {
$scope.cidade = {
id: "",
nome:"",
};
$scope.message = "";
$scope.getCidades = function () {
service.getCidades().then(function (results) {
$scope.cidades = [];
$scope.collection = [];
$scope.cidades = results.data;
$scope.collection = [].concat($scope.cidades);
}, function (err) {
$scope.message = err.error_description;
});
};
//Initializing the list
$scope.getCidades();
}]);
I really don't see anything wrong, but in any case you can add unique param for your request to prevent caching
like
$http.get(serviceBase + 'api/cidades/getall?unique=' + new Date().getTime())

TypeError: Cannot read property 'addTopic' of undefined. Am I blind?

since I've been staring at this problem for some days now, I'm kinda new at AngularJS, I thought maybe someone here could help me. So to my problem:
I get a Typeerror when i try to save a new topic on a forum I'm creating: My controller
module.controller('newTopicController', ['$scope', '$http', 'dataService', function ($scope, $http, $window, dataService) {
$scope.newTopic = {};
$scope.save = function () {
dataService.addTopic($scope.newTopic)
.then(function () {
$window.location = "/#";
},
function () {
alert("couldnt save topic");
});
};
}]);
And my factory:
module.factory("dataService", function ($http, $q) {
var _topics = [];
var _isInit = false;
var _isReady = function () {
return _isInit;
};
var _getTopics = function () {
var deferred = $q.defer();
$http.get("/api/topics?withReplies=true")
.then(function (result) {
angular.copy(result.data, _topics);
_isInit = true;
deferred.resolve();
},
function () {
deferred.reject();
});
return deferred.promise;
};
var _addTopic = function (newTopic) {
var deferred = $q.defer();
$http.post("/api/topics", newTopic)
.then(function (result) {
var createdTopic = result.data;
_topics.splice(0, 0, createdTopic);
deferred.resolve(createdTopic);
},
function () {
deferred.reject();
});
return deferred.promise;
};
return {
topics: _topics,
getTopics: _getTopics,
addTopic: _addTopic,
isReady: _isReady
};
});
So when i try to add a topic to the forum I just get "TypeError: Cannot read property 'addTopic' of undefined" in the controller, right where dataService.addTopic($scope.newTopic) is.
I also have another controller who also uses the factory, but that shouldnt be a problem right?
Thanks for your time.
This seems incorrect:
module.controller('newTopicController', ['$scope', '$http', 'dataService', function ($scope, $http, $window, dataService) {...}
Change it to:
module.controller('newTopicController', ['$scope', '$http', '$window', 'dataService', function ($scope, $http, $window, dataService) {...}

Angularjs calling factory changes $scope

first of all thank you for your time.
I'm having this issue, and I don't know really well why it is.
main
.controller('MainSelectsCtrl', function($scope, $rootScope, $stateParams, $state, $http, $ionicPopup, $translate, $ionicHistory, Auth, ajax, Data, sections, utils) {
var filterBarInstance;
_initController = function () {
$rootScope.icon_sections = _searchIcon($ionicHistory.currentStateName().split(".")[1])
if (Auth.isLoggedIn()) {
PARENT = $scope.$parent
}
}
...
_initController();
and
main
.controller('MainSelectsCtrl', function($scope, $rootScope, $stateParams, $state, $http, $ionicPopup, $translate, $ionicHistory, Auth, ajax, Data, sections, utils) {
var filterBarInstance;
_initController = function () {
$rootScope.icon_sections = _searchIcon($ionicHistory.currentStateName().split(".")[1])
if ($scope.isLogged) {
PARENT = $scope.$parent
}
}
....
initController();
If I use $scope.isLogged, PARENT is ok and I can access later to a desired method.
If I use Auth.isLoggedIn() I don't know why but $scope.$parent changes.
Here is the factory auth:
angular.module('auth.services', [])
.factory('Auth', function () {
var _user = JSON.parse(window.localStorage['session']);
var setUser = function (session) {
_user = session;
window.localStorage['session'] = JSON.stringify(_user);
}
return {
setUser: setUser,
isLoggedIn: function () {
return _user ? true : false;
},
getUser: function () {
return _user;
},
logout: function () {
window.localStorage.removeItem("session");
_user = null;
}
}
});
Thank you very much

Dynamic injection angularjs?

i am using one of the basic concept of angularjs that child controller inherit from parent controller. so i have writen the following code :
var editChannelCtrl = function ($scope, $route, $location, youtube) {
$scope.loading = false;
$scope.saved = false;
$scope.errors = [];
if (angular.isDefined($route.current.params.id)) {
$scope.isOldChannel = true;
$scope.isNewChannel = false;
} else {
$scope.isNewChannel = true;
$scope.isOldChannel = false;
}
};
editChannelCtrl.$inject = ['$scope', '$route', '$location', 'youtube'];
editChannelCtrl.resolve = {
channel: ['ServiceChannel' , function (ServiceChannel) {
return ServiceChannel.ChannelLoader();
}]
};
var oldChannelCtrl = function ($scope, $location, channel) {
$scope.channel = channel;
};
oldChannelCtrl.$inject = ['$scope' , '$location', 'channel'];
var newChannelCtrl = function ($scope, $location, Channel) {
$scope.channel = {
id: null,
version: 1
};
};
newChannelCtrl.$inject = ['$scope' , '$location', 'Channel'];
and for routes what i do , that i resolve the channel that load the channel for the edit form with the following code.
.when('/admin/refactor/channel/edit/:id', {
controller: editChannelCtrl,
templateUrl: '/admin/assets/views/channelForm.html',
resolve: editChannelCtrl.resolve
})
.when('/admin/refactor/channel/new', {
controller: editChannelCtrl,
templateUrl: '/admin/assets/views/channelForm.html'
})
but i don't know why angularjs don't figure how to inject channel to oldChannelCtrl ?

Categories

Resources