I'm new with backbone, and also marionette. Idk why I'm get this error. My structure seems correct, but the error persists.
This is my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css/main.css">
</head>
<body>
<!-- Main App -->
<div id="main-area"></div>
<!-- Templates -->
<script id="main-tpl" src="templates/main.tpl" type="text/x-template"></script>
<!-- 3rd party Dependencies -->
<script src="vendor/jquery/dist/jquery.js"></script>
<script src="vendor/underscore/underscore.js"></script>
<script src="vendor/backbone/backbone.js"></script>
<script src="vendor/backbone.wreqr/lib/backbone.wreqr.js"></script>
<script src="vendor/backbone.babysitter/lib/backbone.babysitter.js"></script>
<script src="vendor/marionette/lib/backbone.marionette.js"></script>
<script type="text/javascript">
// External templates load
_.each(document.querySelectorAll('[type="text/x-template"]'), function (el) {
$.get(el.src, function (res) {
el.innerHTML = res;
});
});
var App = new Backbone.Marionette.Application();
_.extend(App, {
Controller: {},
View: {},
Model: {},
Page: {},
Scrapers: {},
Providers: {},
Localization: {}
});
App.addRegions({
Main: '#main-area'
});
App.addInitializer(function (options) {
var mainView = new App.View.Main();
try {
App.Main.show(mainView);
} catch(e) {
console.error('Error on Show Main: ', e, e.stack);
}
});
App.View.Main = Backbone.Marionette.Layout.extend({
template: '#main-tpl'
});
(function(App) {
'use strict';
App.start();
})(window.App);
</script>
</body>
and my template/main.tpl is only test html.
<div>sounds</div>
All 3rd party dependencies paths are correct.
The error that appears is this:
Error: Could not find template: '#main-tpl'
Can someone tell me where am I wrong?
Thanks.
EDIT:
I think the problem is because $.get is async and the template load after backbone try to render, how can I solve this?
You can update your HTML and replace
<script id="main-tpl" src="templates/main.tpl" type="text/x-template"></script>
with
<script id="main-tpl" type="text/html">
--- template code ---
</script>
Or use requireJs !text plugin to load template files into marionette views.
The problem is that the template loads after the app initialization.
Instead, try this:
$(function () {
var tplList = document.querySelectorAll('[type="text/x-template"]');
var tplCounter = 0;
_.each(tplList, function (el) {
$.ajax({
'url': el.src,
success: function (res) {
el.innerHTML = res;
++tplCounter;
if(tplCounter == tplList.length){
App.start();
}
}
});
});
});
define(['marionette','tpl!cell.tpl'],function(tpl){
var Mn = Backbone.Marionette;
var MyView = Mn.View.extend({
className: 'bg-success',
template: tpl,
regions: {
myRegion: '.my-region'
}
});
})
var model = new Backbone.Model({});
var myView = new MyView({model:model});
Related
gulpfile.js
gulp.task('index', function() {
var target = gulp.src('./app/index.html');
// It's not necessary to read the files (will speed up things), we're only after their paths:
var sources = gulp.src(['./app/js/**/*.js'], {
read: false
});
return target.pipe(inject(sources))
.pipe(inject(gulp.src('./app/js/**/*.js', { read: false }, { ignorePath: '/app/' })))
.pipe(gulp.dest('./build'));
});
index.html
<body ng-app="kisanApp">
<ng-view></ng-view>
<!-- inject:js -->
<script src="/app/js/app.js"></script>
<script src="/app/js/directives.js"></script>
<script src="/app/js/filters.js"></script>
<script src="/app/js/services.js"></script>
<script src="/app/js/controller/driverController.js"></script>
<script src="/app/js/controller/driversController.js"></script>
<!-- endinject -->
</body>
Here I am getting app/js/app.js rather than js/app.js. How should I modify my path so that it works perfectly?
If I understand you correctly this will solve your problem.
var gulp = require('gulp')
inject = require('gulp-inject');
gulp.task('index', function() {
gulp.src('./app/index.html')
.pipe(inject(gulp.src('./app/**/*.js', {read: false}), {ignorePath: 'app', addRootSlash: false}))
.pipe(gulp.dest('./build'));
});
My application is executed successfully without maninSvc.js. After adding this file I'm seeing errror:
angular.min.js:123 Error: [$controller:ctrlreg] http://errors.angularjs.org/1.6.5/$controller/ctrlreg?p0=MainController
at angular.min.js:7
My Code:
Index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<title></title>
<script src="Scripts/jquery-3.2.1.min.js"></script>
<script src="Scripts/bootstrap-3.3.7/js/bootstrap.min.js"></script>
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/angular-route.min.js"></script>
<script src="Scripts/angular-resource.min.js"></script>
<link href="Scripts/bootstrap-3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="Css/Shared.css" rel="stylesheet" />
<script src="MainController.js"></script>
<script src="mainSvc.js"></script>
</head>
<body ng-controller="MainController as vm">
<div data-ng-if="vm.success" class="success">{{vm.success}}</div>
<div data-ng-if="vm.catch" class="catch">{{vm.catch}}</div>
<div data-ng-if="vm.finally" class="finally">{{vm.finally}}</div>
</body>
</html>
MainController.js
(function() {
angular
.module('app', ['ngRoute'])
.controller('MainController', mainController);
mainController.$inject = ['mainSvc'];
function mainController(mainSvc) {
var vm = this;
mainSvc.getData()
.then(function(data) {
vm.success = "success";
}).catch(function(response) {
vm.catch = "catch";
}).finally(function() {
vm.finally = "finally";
});
}
})();
mainSvc.js
(function() {
angular
.module('app', [])
.factory('mainSvc', mainSvc);
mainSvc.$inject = ['$resource'];
function mainSvc($resource) {
var ResourceData = $resource({
query: {
isArray: true
},
get: {},
save: {
method: 'POST'
},
update: {
method: 'PATCH'
},
put: {
method: 'PUT'
},
remove: {
method: 'DELETE'
}
});
return {
getData: getData,
};
function getData() {
/// <summary>
/// Gets Data
/// </summary>
return ResourceData
.get()
.$promise;
}
}
})();
Your mainSvc.js should not have empty dependencies to the module, Then it will be considered as a new module. change it as
(function () {
angular
.module('app')
.factory('mainSvc', mainSvc);
I'm fairly new to coding, but have used Gulp a few times successfully, so I'm unsure what I'm doing wrong. In trying to solve this on my own I've deleted node_modules and re-installed, updated my CDNs to the latest versions, (temporarily) disabled any minification of js and css, and double checked my file paths are cited correctly. Also, prior to using Gulp all file paths to scripts were hardcoded in index.html and worked fine.
Currently Gulp seems to be compiling in my IDE(atom), but when I use nodemon, and go to localhost, my site is broken. The errors inspector gives me are:
GET http://localhost:5000/bundle.css localhost/:23
GET http://localhost:5000/bundle.js angular.js:38
Uncaught Error: [$injector:modulerr]
Here's what my file structure looks like
And here's my code:
//index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./bundle.css" media="screen" title="no title">
<title></title>
</head>
<body>
<ui-view></ui-view>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.4.2/angular-ui-router.js"></script>
<script src="./bundle.js"></script>
</body>
</html>
//gulpfile.js
var gulp = require('gulp');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var annotate = require('gulp-ng-annotate');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var cssmin = require('gulp-cssmin');
var htmlmin = require('gulp-htmlmin');
var watch = require('gulp-watch');
var paths = {
jsSource: ['./public/js/**/*.js'],
sassSource: ['./public/styles/**/*.scss'],
indexSource: ['./public/index.html'],
routesSource: ['./public/routes/**/*.html']
};
gulp.task('sass', function () {
return gulp.src(paths.sassSource)
.pipe(sass())
.pipe(concat('bundle.css'))
.pipe(gulp.dest('./dist'));
});
gulp.task('js', function() {
return gulp.src(paths.jsSource)
.pipe(concat('bundle.js'))
// .pipe(annotate())
// .pipe(uglify())
// .pipe(rename({extname: ".min.js"}))
.pipe(gulp.dest('./dist'))
});
gulp.task('routes', function() {
gulp.src(paths.routesSource)
.pipe(htmlmin({collapseWhitespace: true}))
.pipe(gulp.dest('./dist/routes'))
})
gulp.task('index', function() {
gulp.src(paths.indexSource)
.pipe(htmlmin({collapseWhitespace: true}))
.pipe(gulp.dest('./dist'))
})
gulp.task('watch', function() {
gulp.watch(paths.jsSource, ['js']);
gulp.watch(paths.sassSource, ['sass']);
gulp.watch(paths.indexSource, ['index']);
gulp.watch(paths.routesSource, ['routes']);
});
gulp.task('default', ['js', 'sass', 'watch', 'index'
]);
Also, I was asked to give an example of a decloration of a controller and service.
//homeCtrl
angular.module('app')
.controller('homeCtrl', function ($scope, $state, mainService, homeService, user) {
$scope.user = user;
$scope.addpo = function (ponum) {
homeService.addpo(ponum).then(function (response) {
alert("PO added successfully");
$state.reload('home');
})
};
//homeService
angular.module('app')
.service('homeService', function ($http) {
this.addpo = function (ponumber) {
return $http ({
method: 'POST',
url: '/api/checkin',
data: {
ponumber: ponumber,
checkpoint_id: 1
}
}).then(function (response) {
return response.data;
});
};
});
I believe I have set everything for Angular to work in Phonegap, but apparently the deviceready function is not having the behavior that I expect.
So here is how I set:
index.html
<html ng-app="app">
<head>
<script type="text/javascript" src="js/lib/angular.min.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/lib/ready.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</head>
<body>
<div class="header" ng-controller="HeaderController">
<h3 id="logo"><img src="img/logo.png"/></h3>
<p>{{title}}</p>
<button ng-click="changeTitle()"></button>
</div>
</body>
</html>
app.js
$app = angular.module('app', ['fsCordova']);
$app.config(function($compileProvider){
$compileProvider.urlSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):/);
});
$app.controller('HeaderController', function($scope, CordovaService) {
CordovaService.ready.then(function() {
console.log("Setting the title");
$scope.title = "This title";
$scope.changeTitle = function() {
console.log("Changing the title");
$scope.title = "Title changed";
}
});
});
ready.js from: http://www.ng-newsletter.com/posts/angular-on-mobile.html#native
angular.module('fsCordova', [])
.service('CordovaService', ['$document', '$q',
function($document, $q) {
var d = $q.defer(),
resolved = false;
var self = this;
this.ready = d.promise;
document.addEventListener('deviceready', function() {
resolved = true;
d.resolve(window.cordova);
});
// Check to make sure we didn't miss the
// event (just in case)
setTimeout(function() {
if (!resolved) {
if (window.cordova) d.resolve(window.cordova);
}
}, 3000);
}]);
The title is appearing the way it is {{title}}, not its value. When I click the button, nothing happens, not even the debug logs on the console. Any tips how to set Angular on Phonegap? Thanks.
Apparently on angular 1.2 the urlSanitizationWhitelist doesn't exist anymore.
So I just had to remove the $compileProvider.urlSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):/); line and it worked
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="backbone.js"></script>
<script type="text/javascript" src="jquery-min1.4.js"></script>
<script>
//MODEL CREATION
var person=Backbone.Model.extend(
{
initialize: function()
{
alert("hello backbone");
}
});
function perf()
{
var val=new person();
}
</script>
</head>
<body>
<button onclick="perf()">CLICK</button>
</body>
</html>
This is a simple code, alert is not invoked in the model when an instance of it is created in the perf() function which is called while clicking the button... Please help
Try to write your code in $(function() {}); block or $(document).ready(function () {}); block.
It should work.
You are missing a script reference to Underscore.js
<script type="text/javascript" src="underscore.js"></script>
Backbone requires it as a dependency.
Download it at http://underscorejs.org/ then put it above your script element for backbone.js and it will work fine.
Here's jsfiddle that included both suggestions by dcarson & Naresh J , http://jsfiddle.net/Rvn2L/1/
$(function () {
var person = Backbone.Model.extend({
initialize: function () {
alert("hello backbone");
}
});
function perf() {
console.log('1');
var val = new person();
}
window.perf = perf;
})