I wish to load first service then controller in angular js. But when it first time load the variable of service is empty.
Here is my Service code
app.service('Auth', function($http, $rootScope, $cookies, $sessionStorage, $location, dataFactory) {
var auth = {};
$sessionStorage.logincheck1 = 0;
auth.is_login_sim_v2 = function() {
if ($sessionStorage.logincheck1 == 0) {
var a = document.cookie.substr(10);
var a1 = a.split(";");
dataFactory.post_api('users/loginchecking', {
'session_id': a1[0]
}).then(function(resultChech) {
//console.log(resultChech);
$sessionStorage.logincheck1 = 1;
$sessionStorage.edgar_id = resultChech.checking_id;
$rootScope.$broadcast('Auth:isLoginSuccess');
//console.log($sessionStorage.edgar_id);
if ($sessionStorage.edgar_id === undefined) {
console.log('1');
return false;
} else if ($sessionStorage.edgar_id == 'undefined') {
console.log('2');
return false;
} else if ($sessionStorage.edgar_id == '') {
console.log('3');
return false;
} else {
console.log('4');
return $sessionStorage.edgar_id;
}
});
} else if ($sessionStorage.logincheck1 == 1) {
//console.log(document.cookie.substr(10));
if ($sessionStorage.edgar_id === undefined) {
return false;
} else if ($sessionStorage.edgar_id == '') {
return false;
} else {
return $sessionStorage.edgar_id;
}
}
}
})
And Here is my controller code:
$scope.$on('Auth:isLoginSuccess', function() {
// calculation based on service value
console.log(Auth.is_login_sim_v2());
console.log($sessionStorage.edgar_id);
if (Auth.is_login_sim_v2() == false) {
$scope.isLoggedIn=false;
} else if(Auth.is_login_sim_v2() === undefined){
$scope.isLoggedIn=false;
} else{
$scope.isLoggedIn=true;
}
})
Inject your Service to Controller, and it should work fine.
app.controller('YourController',['$scope', '$rootScope', '$stateParams',
'$location', '$localStorage', '$http', '$cookies', 'Auth',
'$sessionStorage', 'toastr','dataFactory','$ocLazyLoad',
function($scope, $rootScope, $stateParams, $location, $localStorage,
$http, $cookies, Auth,
$sessionStorage, toastr,dataFactory,$ocLazyLoad){
//Your code
// calculation based on service value
console.log(Auth.is_login_sim_v2());
console.log($sessionStorage.edgar_id);
if (Auth.is_login_sim_v2() == false) {
$scope.isLoggedIn=false;
} else if(Auth.is_login_sim_v2() === undefined){
$scope.isLoggedIn=false;
} else{
$scope.isLoggedIn=true;
}
}]);
This will ensure your service is available. Try doing the same dependency injection for you service, which ensures the service initialises properly.
Related
I am trying to create a simple notification system using ngToast through this documentation - http://tamerayd.in/ngToast/. Everything seems to work correctly when using it inside my module(login-flow) but if I'm trying to pass it to a service ($notify) it returns undefined in the console. Thing is that the first time I used this service as a test, it worked. Once I customized it for my needs, the problem appeared. Note that I'm not that good with angularjs and I'm learning it while working on this project. If you notice anything odd or not a "best practice", please, do tell (this part might be a bit offtopic so ignore it if you feel like it).
I've already tried removing any code that felt redundant and also changing parameters orders but the result is the same. Note that this works when using ngToast as a dependency inside the "login-flow" controller but as long as I pass it to the "$notify" service, the problem starts to occur.
app module: index-globals.js
const licentaApp = angular.module("licenta-app", ["ngToast"]);
licentaApp.run(($rootScope, $location) => {
$rootScope.$on('$locationChangeSuccess', function() {
return $location.$$hash;
});
}).controller("app", ($scope, $rootScope, $location) => {
$scope.hash = "";
$rootScope.$on('$locationChangeSuccess', function() {
$scope.hash = $location.$$hash;
});
});
index-login-controller.js - controller which calls the $notify service
licentaApp.controller("login-flow", ($scope, $http, $notify,ngToast) => {
// $scope.username = "admin#admin.com";
// $scope.password = "pass";
$scope.isLoading = false;
$scope.login = () => {
$scope.isLoading = true;
$scope.loading_class = "spinner-border text-light";
$scope.login_text = "";
$http({
url: "attempt-login",
method: "GET",
params: {
username: $scope.email,
password: $scope.password
},
headers: {
"Content-Type": "text/plain"
}
}).then(function(result) {
console.log(ngToast)
if (result.data !== "no_result") {
$notify.displayNotification("Bine ați venit!",ngToast);
location.hash = "profil";
} else {
$notify.displayNotification("Datele de logare nu au fost introduse corect.", ngToast,isError);
}
$scope.isLoading = false;
}).catch(err => {
$notify.displayNotification("A aparut o eroare: " + err);
$scope.isLoading = false;
});
}
$scope.forgotPass = () => {
location.hash = "uitat_parola";
}
});
licentaApp.controller("forgot-pass-flow", ($scope, $rootScope, $location, $http, $timeout, $notify) => {
function verifyCNP(cnp) {
let sum = 0;
controlNumber = "279146358279";
if (cnp.length !== 13) {
$notify.displayNotification($rootScope, $timeout, "Unul dintre codurile numerice este incorect.", true);
return false;
} else {
for (let i = 0; i < 12; i++) {
sum += parseInt(cnp[i]) * parseInt(controlNumber[i]);
}
let controlDigit = sum % 11 === 10 ? 1 : sum % 11;
if (controlDigit !== parseInt(cnp[12])) {
$notify.displayNotification($rootScope, $timeout, "Unul dintre codurile numerice este incorect.", true);
return false;
} else {
return true;
}
}
}
$scope.isLoading = false;
$scope.back = () => {
location.hash = "";
}
$scope.reset = () => {
if ($scope.cnp && $scope.cnp_repeat) {
if (verifyCNP($scope.cnp) === false || verifyCNP($scope.cnp_repeat) === false) {
return;
} else if (!$scope.email || !$scope.email.match(/([A-Z0-9!#$%&'*+-/=?^_`{|}~.])/gi)) {
$notify.displayNotification($rootScope, $timeout, "Email-ul este incorect.", true);
} else {
alert("TEST")
}
} else {
$notify.displayNotification($rootScope, $timeout, "Unul dintre câmpurile de CNP nu a fost completat.", true);
}
}
});
$notify.js - notification service
licentaApp
.service("$notify", function () {
this.displayNotification = (message, ngToast,isError) => {
ngToast.create({
className : isError ? "danger" : "success",
content : message,
dismissOnClick : true,
animation : "slide",
timeout : 5000
});
// console.log(ngToast)
}
});
Nvm - it was something really minor. I was actually sending "isError" as a parameter to the notification system instead of assigning it a value. This feels soooo obvious that I actually feel bad about asking question in the first place.
I have a Sharepoint list I'm trying to get items from and populate in an Angular app. When the page loads, nothing is loaded, if I click off the page and click back the data shows up. How can I get the items to load sooner, like before the page is initially loaded?
Here's my page controller.
app.controller("organizationsCtrl", ["$scope", "$rootScope", "$location", "$routeParams", "spService", "dataService",
function ($scope, $rootScope, $location, $routeParams, spService, dataService) {
$scope.editing = false;
$scope.column = "id";
$scope.reverse = false;
$scope.organizations = dataService.getOrganizations();
$scope.navToAdd = function() {
$location.path("/organizations/add");
}
$scope.navToEdit = function(index) {
$location.path("/organizations/" + index);
};
$scope.sortColumn = function(col) {
$scope.column = col;
if($scope.reverse) {
$scope.reverse = false;
//$scope.reverseclass = 'arrow-up';
} else {
$scope.reverse = true;
//$scope.reverseclass = 'arrow-down';
}
};
}
]);
Here is my service.
app.service('dataService', ['$rootScope', 'spService', function ($rootScope, spService) {
var svc = {};
var organizations = {};
svc.getOrganizations = function() {
spService.getRecords("Organizations", "?$select=ID,Title").then(function (result) {
organizations = result;
});
return organizations;
}
return svc;
}]);
I want to make chat app. So when I send message you can hear pop. So i have two directives, one for my messages and other for simulation. Simulation is working just one time and then stop. I cant get objects from $scope.data to directive myDirective. I really tried almost everything. Is there any solution?
var app = angular.module('myApp', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider,$locationProvider) {
//angular-ui-router
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home',{
url:'/',
views:{
'':{
templateUrl:'../ChatApp/views/chatapp.html'
}
}
})
.state('login',{
url:'/login',
templateUrl:'../ChatApp/views/login.html',
controller: 'LoginController'
});
});
app.controller('MessageController', function($scope,$filter, $http,$state,$timeout,$compile,$interval) {
$scope.randomNumber = Math.floor(Math.random()*(2-0+1)+0);
$scope.data = [];
$scope.name = localStorage.getItem('Name');
console.log(localStorage);
console.log(localStorage.getItem('Name'));
$scope.sendedMessage = "";
$scope.data1 = [$scope.name,$scope.sendedMessage,$scope.date];
//geting data from json
$scope.getData = function () {
$http.get('../ChatApp/data/data.json')
.then(function(response) {
$scope.data =response.data.messages;
console.log($scope.data);
});
};
//logout button
$scope.logout = function () {
localStorage.clear();
console.log(localStorage);
};
//function for rocket button
$scope.sendMessage = function (message) {
$scope.date = new Date();
$scope.date = $filter('date')(new Date(), 'HH:mm:ss');
$scope.message = null;
$scope.sendedMessage = message;
var audio = new Audio('../ChatApp/sounds/videoplayback');
audio.play();
};
//simple autentification
$scope.login = function () {
if(localStorage.getItem('Name') == null){
$state.go('login');
}
};
(function() {
$scope.getData();
$scope.login();
})();
});
app.controller('LoginController', function($scope, $state) {
//simple login
$scope.login = function (name) {
if(name == ""){
alert('Write your name! ');
}
else
{
localStorage.setItem('Name', $scope.name);
$state.go('home');
}
}
});
app.$inject = ['$scope'];
//When you click button rocket, you are adding this to html
app.directive("boxCreator", function($compile){
return{
restrict: 'A',
link: function(scope , element){
if(scope.sendedMessage != undefined && scope.sendedMessage!=null){
element.bind("click", function(e){
var childNode = $compile('<li class="self"><div class="msg"><div class="user">{{:: name}}</div><p>{{:: sendedMessage}}</p><time>{{:: date}}</time></div></li>')(scope);
angular.element( document.querySelector('#chat')).append(childNode);
});
}
//doStuff literally does nothing
scope.doStuff = function(){
alert('hey');
}
}
}
});
app.directive('myDirective', function() {
return {
compile: function(element, attr,$compile) {
var newElement = angular.element('<li class="other"><div class="msg"><div class="user">{{data[randomNumber].name}}</div><p>{{data[randomNumber].message}}</p><time>{{data[randomNumber].date}}</time></div></li>');
element.append(newElement);
var audio = new Audio('../ChatApp/sounds/videoplayback');
audio.play();
return function(scope, element, attr) {
setInterval(function () {
scope.$watch('data', function (data) {
console.log("fff", scope.data);
});
var newElement = angular.element('<li class="other"><div class="msg"><div class="user">{{name}}</div><p>{{scope.data[0].message}}</p><time>{{data[0].date}}</time></div></li>');
element.append(newElement);
var audio = new Audio('../ChatApp/sounds/videoplayback');
audio.play();
},5000);
}
}
}
});
});
I have an Angular 1.5.8 directive with isolated scope and two functions being passed in. I have found that when the names of these functions are all lower case that they work correctly but if they are camelCased then they do not work.
Note that I am talking about the value of the param not the param name itself. here's the html that uses the directive:
<buttons-radio model="contactInformationAcceptable" disabled="approved" callback="personalapprovalfieldchanged()" focus="focuscallback($event)"></buttons-radio>
Note the case of the callback and focus values. If I change these to camel case (and change the function definitions in the parent scope) then they don't work.
Here is the directive:
angular.module("manageApp").directive('buttonsRadio', ['$timeout', function ($timeout) {
return {
restrict: 'E',
scope: {
model: '=',
disabled: '=',
callback: '&',
focus: '&'
},
template: '<div class="form-group yesorno"> ' +
' <div class="col-xs-12">' +
' <button type="button" class="btn btn-success" ng-disabled="disabled" ng-class="{active: yesValue}" ng-click="clickYes()" ng-focus="localFocus($event)">Yes</button>' +
' <button type="button" class="btn btn-danger" ng-disabled="disabled" ng-class="{active: noValue}" ng-click="clickNo()" ng-focus="localFocus($event)">No</button>' +
' </div>' +
'</div>',
controller: function ($scope) {
$scope.$watch('model', function (value) {
if (value) {
if (value == 0) {
$scope.yesValue = false;
$scope.noValue = false;
}
if (value == 1) {
$scope.yesValue = true;
$scope.noValue = false;
}
if (value == 2) {
$scope.yesValue = false;
$scope.noValue = true;
}
}
});
$scope.localFocus = function ($event) {
$scope.focus({ $event: $event });
}
$scope.performCallback = function () {
$timeout(function () {
$scope.callback();
});
}
$scope.yesValue = false;
$scope.noValue = false;
$scope.clickYes = function () {
$scope.yesValue = !$scope.yesValue;
if ($scope.yesValue) {
$scope.noValue = false;
$scope.model = 1;
} else {
$scope.model = 0;
}
$scope.performCallback();
}
$scope.clickNo = function () {
$scope.noValue = !$scope.noValue;
if ($scope.noValue) {
$scope.yesValue = false;
$scope.model = 2;
} else {
$scope.model = 0;
}
$scope.performCallback();
}
}
}
}]);
Edit: Here is the parent controller that has the function I need to use:
angular.module("manageApp").controller('approvalPersonalController', ['$scope', '$http',
function ($scope, $http) {
//personalApprovalFieldChanged personalapprovalfieldchanged
$scope.personalapprovalfieldchanged = function () {
//a field has changed so save them all
console.log('field has changed - do something');
};
}]);
I am confused as to why this is as I have been through a Pluralsight course on directives and the camel case works OK in the plunks that I have created from the course but not in this real world example.
It does work (calls the correct functions at the correct times) but I would like to use camel case for the function names if possible.
Thanks
I have a function and i did it in this way
JS :
function updateInstitution (isValid) {alert('hi')
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'vm.form.institutionForm');
return false;
}
var data = JSON.stringify(vm.institution);
httpService.put('institutions/' + vm.institution_id, data).then(function (results) {
if (results && results.data && results.data.details) {
vm.institution = results.data.details;
formInstitutionData('profile');
commonService.showNotification('success', 'Institution Details updated successfully!');
$('#institutionModal').modal('hide');
}
});
}
}
vm.updateInstitution = updateInstitution;
Html :
<button type="button" class="btn btn-blue" ng-click="vm.updateInstitution(vm.form.institutionForm.$valid)" ng-bind="field.saveText"></button>
But i am getting the error as
updateInstitution is not defined
Can anyone please suggest help.Thanks.
JS :
(function () {
'use strict';
// Institutions controller
angular
.module('institutions')
.controller('InstitutionsController', InstitutionsController);
InstitutionsController.$inject = ['$scope', '$state', '$window', '$timeout', 'httpService', 'Authentication', 'commonService'];
function active() {
httpService.get('institutions/' + vm.institution_id).then(function (results) {
if (results && results.data && results.data.details) {
vm.institutionCopyData = angular.copy(results.data.details);
formInstitutionData('all');
}
});
}
$scope.editInstitutionModal = function (type) {
$scope.field = {};
$scope.showInstitutionModal = false;
if (type === 'basicedit') {
$scope.field.field_type = 'edit-institution.form.client';
$scope.field.formName = 'Edit institution (' + vm.institutionObj.name + ')';
$scope.field.saveText = 'Update';
}
if(type === 'general'){
$scope.field.field_type = 'add-general.form.client';
$scope.field.formName = 'General Info';
$scope.field.saveText = 'Save';
}
$timeout(function () {
$scope.showInstitutionModal = true;
$('#institutionModal').modal('show');
$scope.$apply();
}, 10);
};
function updateInstitution (isValid) {alert('hi')
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'vm.form.institutionForm');
return false;
}
var data = JSON.stringify(vm.institution);
httpService.put('institutions/' + vm.institution_id, data).then(function (results) {
if (results && results.data && results.data.details) {
vm.institution = results.data.details;
formInstitutionData('profile');
commonService.showNotification('success', 'Institution Details updated successfully!');
$('#institutionModal').modal('hide');
}
});
}
}
}
}());
But i am getting the error as
updateInstitution is not defined
Can anyone please suggest help.Thanks.
But i am getting the error as
updateInstitution is not defined
Can anyone please suggest help.Thanks.
You should declare the following in your controller:
var vm = this;
vm.updateInstitution = updateInstitution;
you use $scope.updateInstitution instead of function updateInstitution() , because communication bridge between html and controller is $scope,
or for use vm.function you defined $scope.vm
$scope.updateInstitution = function(){
//Your code
}