I want to implement ngRoute in my angularjs project. But <ng-view></ng-view> doesn't show anything. I read all other posts about this problem, but my problem is not resolved.
I define $routeProvider in app.js file as follows:
'use strict'
angular.module('confusionApp', ['ngRoute'])
.config(['$routeProvider',function($routeProvider) {
$routeProvider
.when('/contactus', { // route for the contactus page
templateUrl : 'contactus.html', controller : 'ContactController'
})
.when('/menu', { // route for the menu pag
templateUrl : 'menu.html', controller : 'MenuController'
})
.when('/menu/:id', { // route for the dish details pag
templateUrl : 'dishdetail.html', controller : 'DishDetailController'
})
.otherwise('/contactus');
}]);
My controllers.js file includes the defenition of all my controllers:
angular.module('confusionApp')
.controller('MenuController', ['$scope','menuFactory',function($scope,menuFactory){
$scope.dishes = menuFactory.getDishes();
//other codes which deleted for simplicity
}])
.controller('dishDetailController',['$scope','$routeParams',
'menuFactory', function($scope,$routeParams,menuFactory){
var dish = menuFactory.getDish(parseInt($routeParams.id,10));
this.dish = dish;
//other codes which deleted for simplicity
}])
.controller('contactController',['$scope',function($scope){
//some code here
}])
.controller('feedbackController',['$scope',function($scope){
//some code here
}]);
And I defined factory in services.js file as follows:
angular.module('confusionApp')
.factory('menuFactory',function(){
var menufac = {};
var dishes=[{... some data ...}];
menufac.getDishes = function(){
return dishes;
};
menufac.getDish = function(index){
return dishes[index];
};
return menufac;
});
In my index.html page <ng-view></ng-view> doesn't show anything.for example when I click on menu tab, url become like this and menu data didn't reload:
http://localhost/conFusion/#!/contactus#%2Fmenu
my default page is contactus.
Also I define scripts in index.html as follows and all the paths are true.
<script src="../bower_components/angular/angular.min.js"></script>
<script src="../bower_components/angular-route/angular-route.min.js"></script>
<script src="scripts/app.js"></script>
<script src="scripts/controllers.js"></script>
<script src="scripts/services.js"></script>
Related
I'm using a helper method to render a template, like so:
module.exports = (Handlebars) => {
Handlebars.registerHelper('foo', () => {
var template = require('../path/to/template.hbs')
return template;
})
}
In the rendered template, I'd like to call another helper, bar.
// template.hbs
<div>
{{foo}}
</div>
// bar.js
module.exports = (Handlebars) => {
Handlebars.registerHelper('bar', ()=> {
// do something here
}
}
But the rendered template seems to have no visibility of the helper, i.e. bar isn't called. What's a good way to get around this?
I'm trying to use the component concept for UI5 and have just built the below:
Index.html snippet:
<script src="resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-libs="sap.m"
data-sap-ui-theme="sap_bluecrystal"
data-sap-ui-resourceroots='{
"sap.ui.ui5test.myapp": "./"
}'>
</script>
<!-- only load the mobile lib "sap.m" and the "sap_bluecrystal" theme -->
<script>
new sap.m.Shell({
app : new sap.ui.core.ComponentContainer({
name : "sap.ui.ui5test.myapp"
})
}).placeAt("content");
</script>
Component.js snippet:
jQuery.sap.declare("sap.ui.ui5test.myapp.Component");
sap.ui.core.UIComponent.extend("sap.ui.ui5test.myapp.Component", {
createContent : function() {
var oView = new sap.ui.core.mvc.View({
id : "testview",
name : "sap.ui.ui5test.myapp.views.FirstView",
type : "JS",
viewData : {component : this}
});
var jsonModel = new sap.ui.model.json.JSONModel();
jsonModel.loadData('http://api.openweathermap.org/data/2.5/weather?q=Auckland');
//jsonModel.loadData('http://api.openweathermap.org/data/2.5/group?id=524901,703448,2643743&units=metric');
sap.ui.getCore().setModel(jsonModel);
oView.setModel(jsonModel);
}
});
In the above snippet for component.js, if I return the view as return oView; it is giving me an error saying "Uncaught TypeError: undefined is not a function". It goes away as soon as I remove the return statement.
If I dont return the view will it navigate to the view I instantiated and loaded above? As I see in the chrome developer tools, I do not seem to find the js file for FirstView to open it as I think it is not getting loaded.
Please suggest how to correct this and how to navigate further.
Awaiting your prompt responses eagerly.
Cheers,
AW
I checked your FirstView.js. Please do the following in your return statement:
return this.app;
As there is no local variable called app, if you write return app, then app is undefined.
Please use sap.ui.view in your createContent method:
var oView = new sap.ui.view({
id : "testview",
viewName : "sap.ui.ui5test.myapp.views.FirstView",
type : "JS",
viewData : {component : this}
});
I'm using handlebars with nodejs and express. This is my main.handlebars file:
<!doctype html>
<html>
<head>
...
</head>
<body>
<div class ="container">
...
<footer>
© {{copyrightYear}} Meadowlark Travel
</footer>
</div>
</body>
</html>
So far I'm passing the copyright year to every route:
var date = new Date();
var copyrightYear = date.getFullYear();
app.get(
'/',
function( req, res) {
res.render(
'home',
{
copyrightYear: copyrightYear
}
);
}
);
Is it possible to set the copyrightYear variable globally, so I don't have to pass it on to every route/view?
ExpressJS provides some kind of "global variables". They are mentioned in the docs: app.locals. To include it in every response you could do something like this:
app.locals.copyright = '2014';
For this case, you can alternatively create a Handlebars helper. Like this:
var Handlebars = require('handlebars');
Handlebars.registerHelper('copyrightYear', function() {
var year = new Date().getFullYear();
return new Handlebars.SafeString(year);
});
In the templates, just use it as before:
© {{copyrightYear}} Meadowlark Travel
Using express-handlebars is just a little bit different:
var handlebars = require('express-handlebars').create({
defaultLayout:'main',
helpers: {
copyrightYear: function() {
return new Date().getFullYear();
},
}
});
toastr is showing an odd behavior -- it's being displayed in a rather ugly way, and I am not overriding anything. No options are given on how to style, but still I am getting this ugly notification.
This is what it looks like:
I am pulling toastr through requireJS; I don't know if that even matters.
logger.js
define(['durandal/system', 'toastr'], function (system, toastr) {
var logger = {
log: log,
logError: logError
};
return logger;
function log(message, data, source, showToast) {
logIt(message, data, source, showToast, 'info');
}
function logError(message, data, source, showToast) {
logIt(message, data, source, showToast, 'error');
}
function logIt(message, data, source, showToast, toastType) {
source = source ? '[' + source + '] ' : '';
if (data) {
system.log(source, message, data);
} else {
system.log(source, message);
}
if (showToast) {
if (toastType === 'error') {
toastr.error(message);
} else {
toastr.info(message);
}
}
}
});
main.js
requirejs.config({
baseUrl: '../Scripts',
paths: {
'services': '../App/services',
'viewmodels': '../App/viewmodels',
'views': '../App/views',
'config': '../App/config',
'durandal': 'durandal',
'plugins': 'durandal/plugins',
'transitions': 'durandal/transitions',
'text': 'text',
'toastr': 'toastr'
}
});
define('jquery', function () { return jQuery; });
define('knockout', ko);
define('main', ['durandal/system', 'durandal/app', 'durandal/viewLocator', 'plugins/router', 'services/logger'], function (system, app, viewLocator, router, logger) {
//>>excludeStart("build", true);
system.debug(true);
//>>excludeEnd("build");
app.title = 'Prepare to die';
app.configurePlugins({
router: true,
dialog: true,
widget: true
});
app.start().then(function () {
// Router will use conventions for modules
// assuming viewmodels/views folder structure
router.makeRelative({ moduleId: 'viewmodels' });
// Replace 'viewmodels' in the moduleId with 'views' to locate the view.
// look for partial views in a 'views' folder in the root.
viewLocator.useConvention();
// Show the app by setting the root view model for our application with a transition.
app.setRoot('viewmodels/shell', 'entrance');
// Override bad route behavior to write to
// console log and show error toast
router.handleInvalidRoute = function (route, params) {
logger.logError('No route found', route, 'main', true);
};
});
});
shell.js
define(['durandal/system', 'services/logger', 'plugins/router', 'config'],
function (system, logger, router, config) {
var shell = {
activate: activate,
router: router
};
return shell;
function activate() {
logger.log('Application is Loaded!', null, system.getModuleId(shell), true);
router.map(config.routes).buildNavigationModel();
return router.activate();
}
});
shell.html
<div>
<header>
<!-- ko compose: {view: 'navigation'} -->
<!-- /ko -->
</header>
<section id="content" class="main container-fluid">
<!-- ko compose: {model: router.activeItem, afterCompose: router.afterCompose} -->
<!-- /ko -->
</section>
</div>
Just as a sidebar, we use toastr under Durandal and I know from John Papa's writings that he feels that third-party frameworks should be loaded globally, while our own modules should be loaded modularly. Just food for thought. I can tell that switching to a global model for third-party frameworks eliminated a lot of esoteric issues.
A quick work-around fix is to do the following:
toastr.options.toastClass = 'toastr';
I've got template file loaded by Require.js via this:
main-app.js
define([
'backboneLoader',
'handlebars',
'text!templates/main.html',
'text!appdata.json'
],
function(
Backbone,
Handlebars,
MainTemplate,
AppData
) {
"use strict";
return Backbone.View.extend({
initialize : function() {
this.render();
},
render : function() {
var template = Handlebars.compile(MainTemplate);
var output = template(AppData);
this.$el.append(output);
console.log("appData:\n" + AppData);
console.log("MainTemplate:\n" + MainTemplate);
console.log("Output:\n" + output);
//smth extra
return this;
}
});
}
);
MainTemplate (main.html)
<ul>
<li><b>Version:</b> {{version}}</li>
<li><b>Author:</b> {{author}}</li>
</ul>
AppData (appdata.json)
{version: "0.0.1", author: "John Doe"}
And output:
<ul>
<li><b>Version:</b></li>
<li><b>Author:</b></li>
</ul>
While expected output:
<ul>
<li><b>Version:</b> 0.0.1</li>
<li><b>Author:</b> John Doe</li>
</ul>
Any ideas what am I doing wrong? Thank you!
UPD:
Problem solved. Here is updated main-app.js:
define([
'backboneLoader',
'handlebars',
'text!templates/main.html!strip',
'text!appdata.json'
],
function(
Backbone,
Handlebars,
mainTemplate,
appData
) {
"use strict";
return Backbone.View.extend({
initialize : function() {
this.render();
},
render : function() {
var template = Handlebars.compile(mainTemplate);
var output = template(eval("(" + appData + ")")); //Object is expected by template(), not JSON.
this.$el.append(output);
console.log("appData:\n" + appData);
console.log("template:\n" + mainTemplate);
console.log("Output:\n" + output);
//smth extra
return this;
}
});
}
);
The problem is AppData is a string of JSON, not an actual Object. Simply change from:
var output = template(AppData);
to
var output = template(JSON.parse(AppData));
You may need to include json2.js to add JSON support for older browsers (<=IE7).
Here is a jsFiddle repro of your template function, the template transformations seems working, the problem is probably located in the text! function in require.js code, try to debug the text! function.
Try also to add the !strip function when loading the template: 'text!templates/main.html!strip',
The documentation suggests it :For HTML/XML/SVG files, there is another option. You can pass !strip, which strips XML declarations so that external SVG and XML documents can be added to a document without worry.