In my angularjs project, I have the following files:
/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- Custom Libraries -->
<script src="lib/Shake.js"></script>
<!-- your app's js -->
<script src="js/services/CloudDatabases.js"></script>
<script src="js/controllers.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="starter">
<ion-nav-view></ion-nav-view>
</body>
</html>
/js/apps.js
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.StatusBar) {
StatusBar.styleDefault();
}
// Register stopping and starting analytics on app open and close
document.addEventListener("pause", window.analytics.Stop(), false);
document.addEventListener("resume", window.analytics.Start(), false);
// Exit the application if you go offline
document.addEventListener("offline", function(){}, false);
});
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
})
....
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/login');
});
/js/services/CloudDatabases.js
angular.module('starter.services')
.service('CloudDatabases', ['$http', function ($http) {
var urlBase = '/api/customers';
this.getDatabases = function () {
console.log('CloudDatabases.getDatabases();');
return 'test getDatabasesResponse';
};
}])
/js/controllers.js
angular.module('starter.controllers', ['CloudDatabases'])
// Login controller
.controller('LoginCtrl', function($scope, $ionicLoading, $http, $ionicPopup, $rootScope, $state, $ionicViewService, CloudDatabases) {
CloudDatabases.getDatabases();
// Form data for the login modal
$scope.loginData = {};
// Try loading the loing data from storage if the user has already logged in
$scope.loginData.username = window.localStorage['username'] || '';
$scope.loginData.password = window.localStorage['password'] || '';
$scope.loginData.uk = window.localStorage['uk'] || false;
// Perform the login action when the user submits the login form
$scope.doLogin = function() {
// Show the loading overlay so the user knows we are busy
$ionicLoading.show({template: 'Loading...'});
// Save the login data to local storage so if the user closes the app they
// don't have to re-enter it
window.localStorage['username'] = $scope.loginData.username;
window.localStorage['password'] = $scope.loginData.password;
window.localStorage['uk'] = $scope.loginData.uk;
// Build login JSON from form
var login_json = JSON.stringify({auth: {passwordCredentials: {username: $scope.loginData.username, password: $scope.loginData.password}}});
// POST the actual authentication request
$http({
method: 'POST',
url: 'https://identity.api.rackspacecloud.com/v2.0/tokens',
data: login_json,
headers: {'Content-Type': 'application/json'}
}).then(function(response) {
// Save the auth token and tenant id for later use
$rootScope.userData = [];
$rootScope.userData.Token = response.data.access.token.id;
$rootScope.userData.Tenant = response.data.access.token.tenant.id;
$rootScope.userData.RawServices = response.data.access.serviceCatalog;
// Use viewservice to hide back button on next page and remove login from nav stack
$ionicViewService.nextViewOptions({
disableBack: true
});
// Track successful logins
window.analytics.trackFeature("Login.Success");
$ionicLoading.hide();
// Navigate to Servers page
$state.go('app.servers');
},
function(response) {
// Track failed logins
window.analytics.trackFeature("Login.Failure");
$ionicLoading.hide();
});
};
})
....
But this throws an error saying that it can't be injected.
Can anyone help with why that might be? It says that starter.services isn't defined
The error is because of your service definition. You are using service definition without dependency array [] as second parameter. This tells angular to treat it as getter method for module starter.services instead of defining the module. Use below code for starter.services to fix this.
angular.module('starter.services', [])
.service('CloudDatabases', ['$http', function ($http) {
var urlBase = '/api/customers';
this.getDatabases = function () {
console.log('CloudDatabases.getDatabases();');
return 'test getDatabasesResponse';
};
}])
Related
I am trying to display the username "bacon" whenever the user clicks on the button "home" using a vm(view model) in order to transfer the object user which contains the property userName but I get the following error.
app.js:1 Uncaught SyntaxError: Unexpected token <
index.controller.js:1 Uncaught SyntaxError: Unexpected token <
The project has the following hierarchy:
Here is my index.html located at the parent folder ./app
<!DOCTYPE html>
<html>
<head>
<title>MEAN Stack User Registration and Login Example Application</title>
</head>
<body class="container">
<!-- header -->
<header>
<ul class="nav nav-tabs">
<li ng-class="{active: activeTab === 'home'}"><a ui-sref="home">Home</a></li>
</ul>
<div class="flash-message" ng-if="flash">
<div class="{{'alert alert-' + flash.type}}" ng-bind="flash.message"></div>
</div>
</header>
<!-- main -->
<main ui-view></main>
<!-- footer -->
<footer></footer>
<!-- external scripts -->
<!-- application scripts -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="app.js"></script>
<script src="home/index.controller.js"></script>
<!--<script src="app-services/user.service.js"></script>
<script src="app-services/flash.service.js"></script>-->
<!-- <script src="account/index.controller.js"></script>-->
</body>
</html>
Here is my app.js located at the parent folder ./app
(function () {
'use strict';
angular
.module('app', ['ui.router'])
.config(config)
.run(run);
function config($stateProvider, $urlRouterProvider) {
// default route
$urlRouterProvider.otherwise("/");
$stateProvider
.state('home', {
url: '/',
templateUrl: 'home/index.html',
controller: 'Home.IndexController',
controllerAs: 'vm',
data: { activeTab: 'home' }
})
}
function run($http, $rootScope, $window) {
// add JWT token as default auth header
$http.defaults.headers.common['Authorization'] = 'Bearer ' + $window.jwtToken;
// update active tab on state change
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
$rootScope.activeTab = toState.data.activeTab;
});
}
// manually bootstrap angular after the JWT token is retrieved from the server
$(function () {
// get JWT token from server
$.get('/app/token', function (token) {
window.jwtToken = token;
angular.bootstrap(document, ['app']);
});
});
})();
Here is my index.html located at the folder ./app/home
<h1>Hi {{vm.user.firstName}}!!</h1>
Here is my index.controller.js located at the folder ./app/home
(function () {
'use strict';
angular
.module('app')
.controller('Home.IndexController', Controller);
function Controller() {
var vm = this;
vm.user = null;
initController();
function initController() {
var user;
user.firstName = "bacon";
vm.user = user;
// get current user
//UserService.GetCurrent().then(function (user) {
// vm.user = user;
//});
}
}
})();
I have read many tutorials about creating simple modals using angular bootstrap. However, all of the examples seem to be based in single page apps that do not use route provider or other more complex architectural patterns. What specific changes need to be made to the code in this plnkr to enable a modal service to be called through a controller in an app that uses route provider?
The example in the plnkr link above is an app that has:
1.) a route provider with two routes, / and /public1.
2.) A navigation controller handles the table of contents, and thus sits above any/both routes.
3.) A modalService is injected into the navigation controller.
4.) And index.html contains a div with the table of contents that is managed by the navigation controller. A button inside the navigation div in index.html calls the deleteCustomer() method of the controller, which should then cause a modal to appear. What changes need to be made in order for the modal to appear when the button is clicked?
On my devbox, the FireFox debugger is generating the following compilation error when I try to launch the app:
Error: [$injector:modulerr] Failed to instantiate module hello due to:
[$injector:modulerr] Failed to instantiate module navigation due to:
[$injector:modulerr] Failed to instantiate module modalService due to:
[$injector:nomod] Module 'modalService' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.5.0/$injector/nomod?p0=modalService
minErr/<#http://localhost:9000/bower_components/angular/angular.js:68:12
module/<#http://localhost:9000/bower_components/angular/angular.js:2015:1
ensure#http://localhost:9000/bower_components/angular/angular.js:1939:38
module#http://localhost:9000/bower_components/angular/angular.js:2013:1
loadModules/<#http://localhost:9000/bower_components/angular/angular.js:4503:22
forEach#http://localhost:9000/bower_components/angular/angular.js:321:11
loadModules#http://localhost:9000/bower_components/angular/angular.js:4
When I download the plnkr as a zip then unzip it and debug in my devbox browser, the FireFox debugger says that it is not able to instantiate the hello module, which is the root of the plnkr app. The plnkr app thus should be able to recreate the problem as soon as we figure out the simple problem of getting the main module for the app to load. (A comment explaining how would be appreciated.).
THE CODE:
Though the complete code is in the plnkr at the link above, I will also copy sections of the code as follows:
index.html is:
<!DOCTYPE html>
<html>
<head>
<base href="/" />
<link data-require="ui-bootstrap#0.13.1" data-semver="0.13.1" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css" />
<script data-require="ui-bootstrap#0.13.1" data-semver="0.13.1" src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.13.1/ui-bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js" data-semver="1.5.0" data-require="angularjs#1.5.0"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="hello" ng-cloak class="ng-cloak">
<!-- start of content section -->
<h1>Hello Plunker!</h1>
<div ng-controller="navigation" class="container">
<ul class="nav nav-pills" role="tablist" >
<li><a class="label label-success" href="/">Home</a></li>
<li><a class="label label-success" href="/public1">public1</a></li>
</ul>
<!-- modal test follows -->
<p><a href class="btn btn-default btn-lg " ng-click="deleteCustomer()">Click to Delete Customer</a></p>
<!-- end of modal test -->
</div>
<div class="container">
<div ng-view=""></div>
</div>
<!-- end of content section -->
<!-- begin local build files -->
<!-- <script src="script.js"></script> -->
<script src="modalService.js"></script>
<script src="home.js"></script>
<script src="public1.js"></script>
<script src="navigation.js"></script>
<!-- end local build files -->
</body>
</html>
script.js is:
'use strict';
/** * Main module of the application. */
angular
.module('hello', [
'ngAnimate',
'ngRoute',
'ngTouch', 'home', 'public1', 'navigation'
])
.config(function ($routeProvider, $httpProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl : 'home.html',
controller : 'home',
controllerAs: 'home'
})
.when('/public1', {
templateUrl : 'public1.html',
controller : 'public1',
controllerAs: 'public1'
})
.otherwise('/');
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
})
.run([ function() {
}]);
navigation.js is:
'use strict';
angular
.module('navigation', ['modalService', 'ngRoute'])
.controller('navigation', function($scope, modalService, $route) {
$scope.tab = function(route) {
return $route.current && route === $route.current.controller;
};
$scope.deleteCustomer = function () {
var custName = 'Some Random Person';
var modalOptions = {
closeButtonText: 'Cancel',
actionButtonText: 'Delete Customer',
headerText: 'Delete ' + custName + '?',
bodyText: 'Are you sure you want to delete this customer?'
};
modalService.showModal({}, modalOptions).then(function (result) {
//some code will go here. But for now can we just
//get the modal to appear and for the cancel button to work?
});
}
});
And modalService.js is:
'use strict';
angular.module('modalService').service('modalService', ['$modal',
function ($modal) {
var modalDefaults = {
backdrop: true,
keyboard: true,
modalFade: true,
templateUrl: 'modalContent.html'
};
var modalOptions = {
closeButtonText: 'Close',
actionButtonText: 'OK',
headerText: 'Proceed?',
bodyText: 'Perform this action?'
};
this.showModal = function (customModalDefaults, customModalOptions) {
if (!customModalDefaults) customModalDefaults = {};
customModalDefaults.backdrop = 'static';
return this.show(customModalDefaults, customModalOptions);
};
this.show = function (customModalDefaults, customModalOptions) {
//Create temp objects to work with since we're in a singleton service
var tempModalDefaults = {};
var tempModalOptions = {};
//Map angular-ui modal custom defaults to modal defaults defined in service
angular.extend(tempModalDefaults, modalDefaults, customModalDefaults);
//Map modal.html $scope custom properties to defaults defined in service
angular.extend(tempModalOptions, modalOptions, customModalOptions);
if (!tempModalDefaults.controller) {
tempModalDefaults.controller = function ($scope, $modalInstance) {
$scope.modalOptions = tempModalOptions;
$scope.modalOptions.ok = function (result) {
$modalInstance.close(result);
};
$scope.modalOptions.close = function (result) {
$modalInstance.dismiss('cancel');
};
}
}
return $modal.open(tempModalDefaults).result;
};
}]);
see below, happy coding ! :)
In plunker you can set <base href="/" />, you have to script that:
<script>
document.write('<base href="' + document.location + '" />');
</script>
You forgot some script required by ui-bootstrap :
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular-animate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular-route.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular-touch.js"></script>
And you forgot to load ui.bootstrap in your module :
angular.module('modalService', ['ui.bootstrap']).service('modalService', ['$modal', function(){...})
http://plnkr.co/edit/4BiF2SlhOZDrFgMzj31z?p=preview
I know it's something simple but I've been trying for hours and can't see what it is. Here is my imports: `
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
and here is the contents of the app file:
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider
// setup an abstract state for the tabs directive
.state('tab', {
url: '/tab',
abstract: true,
templateUrl: 'templates/tabs.html'
})
// Each tab has its own nav history stack:
.state('tab.dash', {
url: '/dash',
views: {
'tab-dash': {
templateUrl: 'templates/tab-dash.html',
controller: 'DashCtrl'
}
}
})
.state('tab.chats', {
url: '/chats',
views: {
'tab-chats': {
templateUrl: 'templates/tab-chats.html',
controller: 'ChatsCtrl'
}
}
})
.state('tab.chat-detail', {
url: '/chats/:chatId',
views: {
'tab-chats': {
templateUrl: 'templates/chat-detail.html',
controller: 'ChatDetailCtrl'
}
}
})
.state('tab.account', {
url: '/account',
views: {
'tab-account': {
templateUrl: 'templates/tab-account.html',
controller: 'AccountCtrl'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/tab/dash');
});
I haven't even touched the app.js as of yet so I have no idea where the particular error is coming from
Ultimately, this error happens when Angular is not able to instantiate a module. Typically this happens when there's an issue or (perhaps in this case) a missing dependency.
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])
It looks like the starter module is trying to inject starter.controllers and starter.services. However, the scripts referenced in the comments do not appear in your HTML file. Since they don't appear to be used anyway, you could consider removing them
angular.module('starter', ['ionic'])
It also looks you're attempting to use UI Router but, it's not linked in your HTML either - so you'll want to add that as well
<script src="js/angular-ui-router.min.js"></script>
I have a project which utilizes Ionic.io, Cordova and AngularJS. It works nicely on my computer Chrome browser, when I launch it with "ionic serve" on the command prompt. However, when I launch it to my connected android device with "ionic run", all I get is a blank screen. It was supposed to load a login screen. Here is the code:
This is the app.js file
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
var app = angular.module('starter', ['ionic','starter.controllers'])
app.run(function($ionicPlatform, $interval) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
$interval(function(){}, 1000);
})
app.config(function($stateProvider, $urlRouterProvider)
{
$urlRouterProvider.otherwise('/login');
$stateProvider
.state('home',
{
url: '/home',
views:
{
'main_view':
{
templateUrl: 'main.html',
controller: 'appCtrl'
}
}
})
.state('login',
{
url: '/login',
views:
{
'main_view':
{
templateUrl: 'login.html',
controller: 'loginCtrl'
}
}
})
.state('contact',
{
url: '/contact',
views:
{
'main_view':
{
templateUrl: 'contact.html',
controller: 'contactCtrl'
}
}
});
$stateProvider
.state('home.timeline',
{
url: '/timeline',
views:
{
'timeline_tab':
{
templateUrl: 'home_items.html',
controller: 'timelineCtrl'
}
}
})
.state('home.news',
{
url: '/news',
views:
{
'news_tab':
{
templateUrl: 'home_items.html',
controller: 'newsCtrl'
}
}
})
.state('home.bulletins',
{
url: '/bulletins',
views:
{
'bulletins_tab':
{
templateUrl: 'home_items.html',
controller: 'bulletinsCtrl'
}
}
})
.state('home.requests',
{
url: '/requests',
views:
{
'requests_tab':
{
templateUrl: 'home_items.html',
controller: 'requestsCtrl'
}
}
});
});
This is the index.html file, which was supposed to run all the content of the application, starting with the login screen and then changing to the other content screens when logged in
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<!--<base href="http://www.comunicafacil.net/">-->
<!-- inject:js --><script src="js/api/models/User.js"></script><script src="js/api/models/Request.js"></script><script src="js/api/models/News.js"></script><script src="js/api/models/Image.js"></script><script src="js/api/models/Bulletin.js"></script><script src="js/api/models/Area.js"></script><script src="js/vendor/md5.js"></script><script src="js/api/ComunicaFacilAPI.js"></script><script src="js/api/ComunicaFacil.js"></script><!-- endinject -->
<!-- compiled css output -->
<link href="css/login.css" rel="stylesheet">
<link href="css/ionic.app.css" rel="stylesheet">
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/controller.js"></script>
</head>
<body ng-app="starter" ng-controller="indexCtrl">
this is the only text that will be displayed on the app screen
<ion-nav-view name="main_view">
</ion-nav-view>
</body>
The cordova version I'm using is 5.4.1, my device is a Samsung Galaxy Tab II, with Android 4.1.2.
Is there anything I need to change to allow the use of ui-route on android?
Is there any other piece of code needed here to identify the issue?
Try putting your
<!-- inject:js --><script src="js/api/models/User.js"></script><script src="js/api/models/Request.js"></script><script src="js/api/models/News.js"></script><script src="js/api/models/Image.js"></script><script src="js/api/models/Bulletin.js"></script><script src="js/api/models/Area.js"></script><script src="js/vendor/md5.js"></script><script src="js/api/ComunicaFacilAPI.js"></script><script src="js/api/ComunicaFacil.js"></script><!-- endinject -->
After <script src="js/controller.js"></script>
The white screen can be caused by any number of issues - as suggested you might want to use remote debugging with chrome (it's awesome btw) to work our whats wrong. You can also use ionic run -l and then type c to get the logs and see the error that way (phone and computer need to be on same wifi network).
My guess here is that your code is bombing on the device because "angular is undefined" or something similar (the order matters!)
I would like to use i18n and i10n in my Angular app.
I read that Angular-translate can help with this, however, it doesn't work for me.
In my index.html:
<!DOCTYPE html>
<html ng-app="eApp">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="../common/css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="../common/css/style.css" />
<title></title>
</head>
<body ng-controller="AppCtrl">
<div id="container" ng-view></div>
<!--- Libs Js files --->
<script type="text/javascript" src="../vendor/angularjs/angular.min.js"></script>
<script type="text/javascript" src="../vendor/angularjs/angular-route.min.js"></script>
<script type="text/javascript" src="../vendor/angularjs/angular-translate.min.js"></script>
</body>
</html>
In my eApp.js:
var eApp = angular.module('elbitApp', ['ngRoute', 'ui.bootstrap', 'config', 'pascalprecht.translate']);
// configure our routes
eApp.config(["$routeProvider",
function ($routeProvider) {
$routeProvider
// route for the home page
.when('/c', {
templateUrl: 'c/partials/c.html',
controller: 'CController'
})
// route for the about page
.when('/de', {
templateUrl: 'd/partials/dE.html',
controller: 'DEController',
resolve: {
data: function (DDataService) {
return DDataService.loadData().then(function (response) {
return response.data;
});
}
}
})
// route for the contact page
.when('/di', {
templateUrl: 'd/partials/di.html',
controller: 'DIController',
resolve: {
data: function (DDataService) {
return DDataService.loadData().then(function (response) {
return response.data;
});
}
}
}).otherwise({
redirectTo: '/di'
});
}]).config(["$httpProvider",
function ($httpProvider) {
// Configure the $httpProvider to parse date with date transformer
$httpProvider.defaults.transformResponse.push(function (responseData) {
convertDateStringsToDates(responseData);
return responseData;
});
}]).config(["$translateProvider",
function ($translateProvider) {
$translateProvider.translations('en', {
"TITLE": 'Hello',
"FOO": 'This is a paragraph.',
"BUTTON_LANG_EN": 'english',
"BUTTON_LANG_DE": 'german'
});
$translateProvider.translations('de', {
"TITLE": 'Hallo',
"FOO": 'Dies ist ein Paragraph.',
"BUTTON_LANG_EN": 'englisch',
"BUTTON_LANG_DE": 'deutsch'
});
$translateProvider.preferredLanguage('en');
}]);
// main controller that catches resolving issues of the other controllers
eApp.controller('AppCtrl', function ($rootScope) {
$rootScope.$on("$routeChangeError", function (event, current, previous, rejection) {
alert("Cant resolve the request of the controller "); //TODO: add URL + additional data.
})
});
In this file I defined my app and added the $translateProvider and two dictionaries.
Afterwards I got to my deController.js:
eApp.controller('DispatcherEventsController', ['$scope', '$route', '$translate',
function($scope, $route, $translate){
var data = $route.current.locals.data;
$scope.title = $translate.instant("FOO");
$scope.switchLanguage = function(languageKey){
$translate.use(languageKey);
};
}]);
In de.html I added a h1 tag with FOO and in a click I would like to change to German:
<h1>{{title |translate}}</h1>
<h1 translate="{{title}}"></h1>
<button type="button" id="searchButton" class="btn btn-default" ng-click="switchLanguage('de')">German</button>
I don't get any problem, but nothing happens. I expected that the English title will be converted to German title.
What can I do to make this work?
It works well for me. Here is a jsFiddle DEMO.
In this case, you want to bind $scope.title with translation key "FOO".
You should change the value of $scope.title dynamically in the switchLanguage function. Then view will be updated accordingly.
//default value
$scope.title = $translate.instant("HEADLINE");
$scope.switchLanguage = function(key){
$translate.use(key);
$scope.title = $translate.instant("HEADLINE");
}
In my opinion, maybe use translation key is a better way than scope data binding. You don't have to maitain the value of key manually.
<h1>{{'FOO' | translate}}</h1>
According to the error msg you provided, maybe you could check if there is any typo syntax in your controller.
Should be
$translate.use(languageKey)
Not
$translate.uses(languageKey)
Though not directly related to your question - you must remember to set the preferred language in the translations.js file, or whatever its name is that you define your key-value translations. Otherwise it will just default to whatever the key is.
...
GREETING: 'Hello World!',
...
$translateProvider.preferredLanguage('en');
Without this line, when doing this:
<h2>{{'GREETING'|translate}}</h2>
Would appear as just GREETING instead of the 'Hello World.'