AngularJS $translate.refresh() not working on load - angularjs

I'm testing Angular-translate with angular-traslate-partial-loader and it is not populating the page with the default translation on page load.
here is a plunkr of the problem recreated
app.controller('MainCtrl', ['$scope', '$translate', '$translatePartialLoader',
function($scope, $translate, $translatePartialLoader) {
$translatePartialLoader.addPart('test');
$translate.refresh();
$scope.dotranslate = function() {
$translate.refresh();
};
}
]);
http://plnkr.co/edit/Vts9CW4VoJsXoSdllFsq?p=preview
I added a refresh button to show that the $translate.refresh() works after page load.
What am i missing?

I've never used $translate so I'm not sure exactly what the problem is, but you may be changing a value too late in the digest cycle for the refresh to catch it.
You can use $scope.$evalAsync to fix this. See the angular documentation here: https://docs.angularjs.org/api/ng/type/$rootScope.Scope
Here is an example of your app.js with the change:
var app = angular.module('plunker', ['pascalprecht.translate']);
app.config(function run($translateProvider, $translatePartialLoaderProvider) {
$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: 'translation-{lang}-{part}.json'
});
$translateProvider.preferredLanguage('fr-FR');
});
app.controller('MainCtrl', ['$scope', '$translate', '$translatePartialLoader',
function($scope, $translate, $translatePartialLoader) {
$translatePartialLoader.addPart('test');
//I wrapped your refresh in the eval async function
$scope.$evalAsync(function() {
$translate.refresh();
});
$scope.dotranslate = function() {
$translate.refresh();
};
}
]);

Related

Failed to instantiate module myApp due to: Error: [$injector:nomod]

I am having an error on this code. I don't know why I am using angularjs 1.7.x version
$(document).ready(function () {
$('#signupBtn-spinner').hide();
var app = angular.module('myApp', []);
$('#signupBtn').click(signup);
function signup() {
app.controller('signupController', ['$scope', '$http', function ($scope, $http) {
alert('hello')
}]);
}
})
I strongly recommend you to avoid to use jquery with Angular/js
If you want to implement signup/login logic, suggest you to use ui-router. Some example.
Also please read this great Josh David Miller's answer “Thinking in AngularJS” if I have a jQuery background
About your problem:
You get this error from ng-app.
Put var app = angular.module('myApp', []); out of $(document).ready
Angularjs is loaded and it does not see any module because it is still not ready.
var app = angular.module('myApp', []);
$(document).ready(function () {
$('#signupBtn-spinner').hide();
$('#signupBtn').click(signup);
function signup() {
app.controller('signupController', ['$scope', '$http', function ($scope, $http) {
alert('hello')
}]);
}
})

Angular JS: Inject service within app.js

I want the users not to go to certain pages at least they've logged in before. I'm currently using this:
app.run(function ($rootScope, $route, $location)
{
var restrictedPages =
[
'/Survey/', '/Survey/Detalle', '/Survey/Accepted', '/Account/Profile',
'/Auction/Detail', '/Survey/Accepted'
];
$rootScope.$on('$locationChangeStart', function (ev, next, current)
{
var nextPath = $location.path();
var nextRoute = $route.routes[nextPath];
if(restrictedPages.indexOf(nextPath) !== -1)
{
$location.path('/home');
}
});
});
My problem here is that I want to inject inside of this piece of code my AccountService. How can I achieve this? Because the loading-order is the following
app.js (the code presented is inside here)
homeService.js
accountService.js
I truly believe this is not the right way to go but it seems so simple and the only thing I'm missing is the account service injection.
Consider this module, which includes a accountService that uses implicit DI:
angular.module('myApp', [])
.factory('accountService', function($rootScope) {
// $rootScope is implicitly injected
})
.run(['$rootScope', '$route', '$location', 'accountService', function ($rootScope, $route, $location, accountService)
{
var restrictedPages =
[
'/Survey/', '/Survey/Detalle', '/Survey/Accepted', '/Account/Profile',
'/Auction/Detail', '/Survey/Accepted'
];
$rootScope.$on('$locationChangeStart', function (ev, next, current)
{
var nextPath = $location.path();
var nextRoute = $route.routes[nextPath];
if(restrictedPages.indexOf(nextPath) !== -1 && !accountService.isLoggedIn())
{
$location.path('/home');
}
});
}]);
if you want more documentation: https://docs.angularjs.org/guide/di

AngularJS Ionic: Unable to inject Ionic History

I am trying to inject ionic history in my Ionic Project and I am getting this error
Error: [$injector:unpr] http://errors.angularjs.org/1.2.14/$injector/unpr?p0=%24ionicHistoryProvider%20%3C-%20%24ionicHistory
This is my complete controller code
.controller('menu', ['$scope', '$state', '$ionicHistory', function($scope,$state,$ionicHistory) { //first menu
var user = JSON.parse(localStorage.getItem("user"));
$scope.gotoUser = function(){
localStorage.removeItem("selectedName");
localStorage.setItem("selectedName",username);
$state.go("Page");
};
$scope.gotoLogouts = function() {
// localStorage.clear();
$ionicHistory.clearHistory();
//localStorage.removeItem('user');
$state.go("login");
}])
Please what am doing wrong.
Are you using Cordova?
If you are, it is probably happening because you did not inject ngCordova in your module.
Like:
angular.module('anotei', ['ionic', 'ngCordova'])
my friend your problem is not in you $ionicHistory, it is in the locatStorage. you are not injecting the local storage in the controller. Just inject it and it will work.
Cheers.
Try to add the closing curly bracket } for the $scope.gotoLogouts function, just before the last line.
#Nadeem Khoury you should not inject localStorage. It is $localStorage that should be injected but he is using localStorage which should not be injected.
If this is exactly the code you are using, I am with #Ennedigi
.controller('menu', ['$scope', '$state', '$ionicHistory', function($scope,$state,$ionicHistory) { //first menu
var user = JSON.parse(localStorage.getItem("user"));
$scope.gotoUser = function(){
localStorage.removeItem("selectedName");
localStorage.setItem("selectedName",username);
$state.go("Page");
};
$scope.gotoLogouts = function() {
// localStorage.clear();
$ionicHistory.clearHistory();
//localStorage.removeItem('user');
$state.go("login");
}
}])
try to include timeout, location and windows in module
IonicModule
.factory('$ionicHistory', [
'$rootScope',
'$state',
'$location',
'$window',
'$timeout',
'$ionicViewSwitcher',
'$ionicNavViewDelegate',
function($rootScope, $state, $location, $window, $timeout, $ionicViewSwitcher, $ionicNavViewDelegate) {
#Blaze, you have to inject $localStorage in your controller like below,
.controller('menu', ['$scope', '$state', '$ionicHistory', '$localStorage' function($scope,$state,$ionicHistory,$localStorage) { //first menu
var user = JSON.parse(localStorage.getItem("user"));
$scope.gotoUser = function(){
localStorage.removeItem("selectedName");
localStorage.setItem("selectedName",username);
$state.go("Page");
};
$scope.gotoLogouts = function() {
// localStorage.clear();
$ionicHistory.clearHistory();
//localStorage.removeItem('user');
$state.go("login");
}
}])

Advantage of using $injector vs explicit DI declaration AngularJS

Just wondering if there's difference between:
angular.module('app', [])
.controller('myctrl', ['$scope', 'customService',
function($scope, customService) {
// use customService
}
]);
and using $injector
angular.module('app', [])
.controller('myctrl', ['$scope', '$injector',
function($scope, $injector) {
// get customService via injector and use it
$injector.get('customService');
}
]);
Sometimes I need to inject quite a few dependencies and my parameter list ends up to be lengthy. That's why I'm thinking the latter approach may be better for my scenario.
Does the difference affect testing or minification or any other reason?
You are on the right track. Look at John Papa's Style Guide. You will do the injection before the controller function.
/* recommended */
angular
.module('app')
.controller('Dashboard', Dashboard);
Dashboard.$inject = ['$location', '$routeParams', 'common', 'dataservice'];
function Dashboard($location, $routeParams, common, dataservice) {
}
Basically there is not much different, until you first encounter your circular dependency error while loading your module.
Simple Fiddle that demonstrates circular dependency.
Code (from fiddle):
angular.module('app', [])
.service('serviceA', function (serviceB) {
return {};
})
.service('serviceB', function (serviceA) {
return {};
})
.controller('myCtrl', function (serviceA, serviceB) {
});
Using $injector helps prevent that scenario because when you use it inside the Controller/Factory/Service/etc instead of injecting the first way, you are delaying the dependency and therefore solving the problem.
And a simple Fiddle that demonstrates how that problem is solved.
Code (from fiddle):
angular.module('app', [])
.service('serviceA', function (serviceB) {
return {
test: "it works!"
};
})
.service('serviceB', function ($injector) {
return {
test: function() {
var serviceA = $injector.get("serviceA");
return serviceA.test;
}
};
})
.controller('myCtrl', function ($scope, serviceA, serviceB) {
$scope.test = serviceB.test();
});

AngularJS Extending Directive Return

I am really new to Angular... I have been trying to google on how to to do this but I think my lack of knowledge keeps me from wording my question correctly thus I am here.
Here is what I am trying to do with my code
ng.module('app.navigation', [
])
.controller('NavigationController', ['$scope', function($scope, $http, $filter){
$scope.message = "Load in the navigation";
}])
.directive('navigation', function() {
return {
templateUrl: 'navigation.view.html',
cssUrl: 'navigation.css',
link: $.NavbarSlide,
};
});
As you can see in my directive return I have put in a cssUrl... this obviously doesn't exist in Angular so what I am trying to do is figure out how to extend Angular with my own 3rd part extension so that I can do something with "cssUrl".
Took a cue from this project https://github.com/marcoslin/angularAMD
ng.module('app.navigation', [
])
.controller('NavigationController', ['$scope', function($scope, $http, $filter){
$scope.message = "Load in the navigation";
}])
.directive('navigation', function() {
return CustomFunction({
templateUrl: 'navigation.view.html',
cssUrl: 'navigation.css',
link: $.NavbarSlide,
});
});
Don't know why I didn't think of this earlier.

Resources