Angularjs calling factory changes $scope - javascript

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

Related

Share value between views in AngularJS

I have apage with 3 options and each option represent a group of permissions. I have the groupName in my view permissionsConfig but when I edit one group I lose the name of the group and i need the name to make a request to my rest api.
organizationsController.js
app.controller('OrganizationsPermissionsSettingsController',['$rootScope', '$scope', '$modal', 'HelperService', 'AuthService', '$state', '$http', function ($rootScope, $scope, $modal, HelperService, AuthService, $state, $http) {
var controllerScope = $scope;
controllerScope.organizationGroups = [];
$http.get('/api/organization_permissions_groups').success(function (data) {
controllerScope.organizationGroups = data;
});
controllerScope.openOrganizationPermissionsSettings = function (organizationId) {
$state.go('app.organizationPermissionsSettings');
};
var groupId = "";
document.addEventListener("DOMContentLoaded", function(event) {
if(document.getElementById("permissionGroupName").innerHTML!=null){
groupName=document.getElementById("permissionGroupName").innerHTML;
console.log("groupName ",groupName);
$http.get('/api/organization_permissions_groups/getId'+groupName).success(function (data) {
if(data != undefined && data != null){
groupId=data;
console.log("controllerScope.id ",groupId);
}
});
}
});
$scope.navigateToGraphs = function() {
$state.go('app.organizationGraphs', { groupId: groupId });
// then get parameter groupId
$state.params.groupId;
}
$scope.navigateToViews = function() {
$state.go('app.organizationViews', { groupId: groupId });
// then get parameter groupId
$state.params.groupId;
}
}]);
app.controller('OrganizationGraphsController',['$rootScope', '$scope', 'HelperService', '$http', '$stateParams', function ($rootScope, $scope, HelperService, $http, $stateParams) {
var controllerScope = $scope;
controllerScope.graphData = {};
$http.get('/api/organization_permissions_groups/graphs/'+$stateParams.groupId).success(function (data) {
controllerScope.graphData = data.graphs;
});
controllerScope.saveOptions = function () {
$http.put('/api/organization_permissions_groups/graphs/'+$stateParams.groupId, controllerScope.graphData).then(function (response) {
}, function () { });
HelperService.editItem(id, controllerScope.graphData, null, 'Graphs', '/api/organization_permissions_groups/graphs/');
}
$scope.cancel = function () {
$modalInstance.dismiss();
};
}
]);
organizationPermissionsConfigView.html
here I have <td id="permissionGroupName">{{organizationGroup.group_name}}</td> which retrive my permission group name.
I have 3 groups at the moment and with the group name i make a rest api request to get the id and with that id i can make updates on the permission group understand?

AngularJS variable not showing in html

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.

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) {...}

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 ?

Angularjs how to call asyncron service method and how to use a dependency in listener

I want to use a dependency in listener but the websocket was undefined
$rootScope.$on('websocket.connected', function() {
$websocket.request(.....).then();
});
and a want to call a service method (who depend on asyncron method) when it ready
app.controller('MyCtrl', function(myServ, $log) {
myServ.getInfos();
});
thank you.
Code in jsfiddle http://jsfiddle.net/8DHfY/3/ or here
var app = angular.module('myApp', ['myServ'])
.config(['$websocketProvider', function ($websocketProvider) {
$websocketProvider.setHost('ws://echo.websocket.org/');
}])
.controller('MyCtrl', function(myServ, $log) {
$log.log('I want to call myServ.getInfos() from a controler');
});
angular.module('myServ', ['websocket']).service('myServ', ['$log', '$rootScope', '$websocket', function($log, $rootScope, $websocket) {
$log.error('websocket is %o ... ???', $websocket); // return undefined
$rootScope.$on('websocket.connected', function() {
$log.error('websocket is still %o', $websocket); // return undefined
});
return {
getInfos: function() {
$websocket.request(JSON.stringify({'key': 'value'}));
}
};
}]);
angular.module('websocket', []).provider('$websocket', [function() {
var _this = this;
_this.host = '';
_this.connection = null;
_this.setHost = function(host) {
this.host = host;
return this;
};
_this.request = function(request) {
//request method for websocket
};
this.$get = ['$log', '$rootScope', function($log, $rootScope) {
_this.connection = new WebSocket(this.host);
_this.connection.onopen = function(){
$log.log('Websocket connected to %s', _this.host);
$rootScope.$emit('websocket.connected');
};
}];
}]);
Providers invoke the $get function upon injection and use the singleton of whatever is returned from that function.
This means since you do not return anything from the $get function, it uses undefined.
Here's an updated fiddle: http://jsfiddle.net/8DHfY/4/
this.$get = ['$log', '$rootScope', function($log, $rootScope) {
_this.connection = new WebSocket(this.host);
_this.connection.onopen = function(){
$log.log('Websocket connected to %s', _this.host);
$rootScope.$emit('websocket.connected');
};
return _this;
}];

Categories

Resources