I've been trying to learn angularJS, specifically 1.5 using components. My IDE is c9 so the server uses port: process.env.PORT which when I start will show the project at https://projectName-username.c9users.io (with angular-ui-router it has '/#!' on the end). This ide doesn't seem to compile es6 without using something like gulp. So I copy pasted much of the gulp code from the tutorial into my own project so that I could continue using the es6 syntax to build my own project.Everything is working pretty well except I am trying to link bootstrap 4 and my own css files from inside the project rather than a cdn and I can't seem to get the file path correct. When running the gulp file it says serving files from ./build so I tried writing the path from there but it has 404 on the resource.The closest I've come to was no errors thrown trying <link rel="stylesheet" src="#!/src/bower_components/bootstrap/dist/css/bootstrap.min.css"> but checking the network it says it's loading https://billardsWebsite-rawlejuglal.c9users.io/ with type stylesheet but nothing is actually there. Below is my file structure, the index.html file and then the gulpfile. If anyone can enlighten me on how to structure my links to find these resources I would appreciate it.
billardsWebsite
-.c9
-.git
-build
-index.html
-main.js
-node_modules
-src
-bower_components
-boostrap
-dist
-css
-bootstrap.min.css
-js
-css
-styles.css
-index.html
-.bowerrc
-.bower.json
-gulpfile.js
-package.json
-Procfile
Index.html (src/index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<title ng-bind="pageTitle"></title>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="#!/src/bower_components/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
<div ui-view></div>
<!-- jQuery first, then Tether, then Bootstrap JS. -->
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<script src="main.js"></script>
</body>
</html>
gulpfile.js
var gulp = require('gulp');
var notify = require('gulp-notify');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var babelify = require('babelify');
var ngAnnotate = require('browserify-ngannotate');
var browserSync = require('browser-sync').create();
var rename = require('gulp-rename');
var templateCache = require('gulp-angular-templatecache');
var uglify = require('gulp-uglify');
var merge = require('merge-stream');
// Where our files are located
var jsFiles = "src/js/**/*.js";
var viewFiles = "src/js/**/*.html";
var interceptErrors = function(error) {
var args = Array.prototype.slice.call(arguments);
// Send error to notification center with gulp-notify
notify.onError({
title: 'Compile Error',
message: '<%= error.message %>'
}).apply(this, args);
// Keep gulp from hanging on this task
this.emit('end');
};
gulp.task('browserify', ['views'], function() {
return browserify('./src/js/app.js')
.transform(babelify, {presets: ["es2015"]})
.transform(ngAnnotate)
.bundle()
.on('error', interceptErrors)
//Pass desired output filename to vinyl-source-stream
.pipe(source('main.js'))
// Start piping stream to tasks!
.pipe(gulp.dest('./build/'));
});
gulp.task('html', function() {
return gulp.src("src/index.html")
.on('error', interceptErrors)
.pipe(gulp.dest('./build/'));
});
gulp.task('views', function() {
return gulp.src(viewFiles)
.pipe(templateCache({
standalone: true
}))
.on('error', interceptErrors)
.pipe(rename("app.templates.js"))
.pipe(gulp.dest('./src/js/config/'));
});
// This task is used for building production ready
// minified JS/CSS files into the dist/ folder
gulp.task('build', ['html', 'browserify'], function() {
var html = gulp.src("build/index.html")
.pipe(gulp.dest('./dist/'));
var js = gulp.src("build/main.js")
.pipe(uglify())
.pipe(gulp.dest('./dist/'));
return merge(html,js);
});
gulp.task('default', ['html', 'browserify'], function() {
browserSync.init(['./build/**/**.**'], {
server: "./build",
port: process.env.PORT || '3000',
notify: false,
ui: {
port: 3001
}
});
gulp.watch("src/index.html", ['html']);
gulp.watch(viewFiles, ['views']);
gulp.watch(jsFiles, ['browserify']);
});
Related
I'm new to Unit Testing. I have followed the tutorials and I have everything
configured on node.js via npm. I have done some describe and it just to get the feel for ho things are set up and my spec runner is fine. The problem I'm trying to get test on controllers figured out but I run in a snag and been trying to figure things out for a while but I continue to get the same error so I thought I would reach out.
I'm trying to do a simple test on a LoginController but I continue to get the same error. I can't point out what I'm doing wrong. Trying to get over this hurdle.
TypeError: angular.mock.module is not a function:
spec runner index html file.
<!doctype html>
<html>
<head>
<title>Jasmine Spec Runner</title>
<link rel="stylesheet" href="../bower_components/jasmine-core/lib/jasmine-core/jasmine.css">
</head>
<body>
<script src="../My Documents/My Website/AngularLogin-
Registration/js/angular-1.6.0.js"></script>
<script src="../My Documents/My Website/AngularLogin-Registration/js/angular-route-1.6.0.min.js"></script>
<script src="../bower_components/jasmine-core/lib/jasmine-core/jasmine.js"></script>
<script src="../bower_components/jasmine-core/lib/jasmine-core/jasmine-html.js"></script>
<script src="../bower_components/jasmine-core/lib/jasmine-core/boot.js"></script>
<!-- include source files here... -->
<!--<script src="//code.jquery.com/jquery-3.1.1.min.js"></script>-->
<!--<script src="//code.angularjs.org/1.6.0/angular-cookies.min.js"></script>-->
<script src="../My Documents/My Website/AngularLogin-Registration/js/angular-mock.js"></script>
<script src="../My Documents/My Website/AngularLogin-Registration/js/app.js"></script>
<script src="../My Documents/My Website/AngularLogin-Registration/login/login.controller.js"></script>
<!-- include spec files here... -->
<script src="spec/test.js"></script>
Here is my test file.
describe('LoginController test', function () {
beforeEach(angular.mock.module('app'));
beforeEach(angular.mock.inject(function(_$controller_){
$controller = _$controller_;
}));
describe('$scope.grade', function() {
it('sets the strength to "strong" if the password length is >8 chars',
function() {
var $scope = {};
var controller = $controller('LoginController', { $scope: $scope });
$scope.password = 'longerthaneightchars';
$scope.grade();
expect($scope.strength).toEqual('strong');
});
});
});
Thanking You In Advance
PDH
Load angular-mocks library in your spec runner html , make sure to load it after angular.js.
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-mocks.js"></script>
You can also use bower to download the js file instead of the CDN.
running angular js app on ubuntu 14.04 with help of gulp. My folder structure is this
|-- app <--- main application folder
|-- bower_components
|-- bower.json
|-- env <--public folder; copy the main `/app` code while runtime
|-- gulpfile.js
|-- node_modules
`-- package.json
Below are the task. see complete gulpfile.js
I have added below in /app/index.html
<!-- bower:js -->
<!-- endinject -->
inject : inject all bower_components JS into env/index.html
gulp.task('inject', function () {
var target = gulp.src('./app/index.html');
var sources = gulp.src('./app/**/*.js');
return target
.pipe($.inject(gulp.src(mainBowerFiles(), {read: false}),{
name: 'bower',
relative:true}))
.pipe(gulp.dest(src))
});
now here is the issue
Now if I write dest i.e. .pipe(gulp.dest('./env')) in above task , than nothing being added to index.html ( on both /app and /env folder) .
and
If I write src i.e. .pipe(gulp.dest('./app')) than all bower_components js files being added into both index.html ( which I think, because of copy task which runs after inject )
<!-- bower:js -->
<script src="../bower_components/jquery/dist/jquery.js"></script>
<script src="../bower_components/angular/angular.js"></script>
<script src="../bower_components/angular-bootstrap/ui-bootstrap-tpls.js"></script>
<script src="../bower_components/angular-ui-router/release/angular-ui-router.js"></script>
<script src="../bower_components/angular-messages/angular-messages.js"></script>
<script src="../bower_components/ngstorage/ngStorage.js"></script>
<script src="../bower_components/angular-resource/angular-resource.js"></script>
<!-- endinject -->
copy : which first complete browserify task and than copy all /app .html and .css to /env This seems confusing !!
gulp.task('copy', ['browserify'], function() {
gulp.src(['app/**/*.html','./app/**/*.css'])
.pipe(gulp.dest(dest))
.pipe(browserSync.stream());
});
Now when we run gulp ; Firefox opens up but the files inside <!-- bower:js --> are added in page but browser can not find sources of these files. Kindly guide me
Do I need to use wiredep or useref gulp modules or am I missing something here.
I fixed this by the
ordering of task( copy before inject)
and changing in browser-sync
gulp.task('inject', ['lint', 'copy'] , function () {
var target = gulp.src('./app/index.html');
var minify_js = gulp.src('./app/**/*.js')
.pipe($.sourcemaps.init())
.pipe($.plumber())
.pipe($.uglify({ mangle: false, compress:true, output: { beautify: false } }).on('error', onError))
.pipe($.plumber.stop())
.pipe($.concat('vendor.js'))
.pipe($.rename({suffix: '.min'}))
.pipe($.sourcemaps.write())
.pipe(gulp.dest(dest));
return target
.pipe($.inject(
gulp.src(mainBowerFiles(),{read: false}), {name: 'bower', relative: true}))
.pipe($.inject(minify_js,{relative: true}))
.pipe($.inject(
gulp.src('bower_components/**/*.css', {read: false}), {relative: true}))
.pipe(gulp.dest(dest))
});
and
gulp.task('browser-sync', ['inject'], function() {
browserSync.init({
server: {
baseDir: './env',
routes: {
"/env" : "env",
"/bower_components" : "bower_components"
}
},
browser: ["chromium-browser"]
});
});
here is complete gulpfile, hope it helps someone. Thanks
I'm trying to send local notifications for every day at 7 am. I have placed the below code in controller,
Code
function send_push_notification (){
cordova.plugins.notification.local.schedule({
id: 10,
title: "Report",
text: "Pls send a report :-)",
firstAt: alarm_time,
at: at_8_am,
every: "day"
}).then(function (success) {
return true;
}, function (err) {
return false
});
}
But it shows ReferenceError: cordova is not defined.. I have defined
<script src="cordova.js"></script> at very first in my app's index.html file.
I also tried the example given in this http://ngcordova.com/docs/plugins/localNotification/ link. But donno which one to follow. Both are totally different.
Update:
cordova.plugins.notification.local.schedule method only works inside deviceready event listener but not in the controller. I should make it to work on controller..
ie, I have a task of sending local push notification when there is no database update made for that particular date else no need for notification.
The following sample code should get you started in sending local notifications in Android and iOS device.
index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link rel="stylesheet" type="text/css" href="css/index.css">
<title>Hello World</title>
</head>
<body>
<h3>Local Notification</h3>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
index.js
$(document).ready(function() {
document.addEventListener("deviceready", onDeviceReady, false);
});
function onDeviceReady() {
try {
cordova.plugins.notification.local.schedule({
text: "This is the text.",
at: new Date(new Date().getTime() + 10000)
});
} catch (e) {
alert("Fail " + e);
}
}
The following sample code sends out a test notification on 10th second after launching the app. The code is tested in Android and iOS devices. The above sample code is available in the github page. You can download the sample app, install notification plugin and test the same.
As suggested in my source, the following command could be used to have a forked and modified push plugin to work in your project:
cordova plugin add https://github.com/zxshinxz/PushPlugin.git
The default push plugin needs to be removed and this will be its replacement. If I understood correctly the post below, this solution fixes local notification usage also when the program is turned off.
More info on that linked post.
My source:
Cordova local notification doesn't work while app is in background
Here is a steps for running local notifications on cordova
Step : 1
Type in cmd prompt of your folder
bower install ngCordova
include in your main index.html file before cordova
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>
Step:2
Inject dependency
angular.module('myApp', ['ngCordova'])
Install this plugin
cordova plugin add https://github.com/katzer/cordova-plugin-local-notifications.git
Step:3
Here is schedule.js local notification file used in your controller
(function(){
'use strict';
angular.module('myApp').controller('Schedule',['$scope','$ionicPlatform','$rootScope','$cordovaLocalNotification','$cordovaSms',Schedule]);
function Schedule($scope,$ionicPlatform,$rootScope,$cordovaLocalNotification,$cordovaSms){
//************************Setting Notification***********************
$ionicPlatform.ready(function() {
var now = new Date().getTime();
var _10SecondsFromNow = new Date(now + 10 * 1000);
$cordovaLocalNotification.schedule({
id: 10,
title: 'Report',
text: 'Text here',
at: _10SecondsFromNow
}).then(function (result) {
// ...
});
};
$cordovaLocalNotification.add({
id: 10,
title: 'Report',
text: 'Pls send a report :-)',
firstAt: at_8_am,
every: 'day'
}).then(function (result) {
// ...
});
$scope.scheduleSingleNotification = function () {
$cordovaLocalNotification.schedule({
id: 1,
title: 'Title here',
text: 'Text here',
}).then(function (result) {
// ...
});
};
});
//*******************Notification Ended***********************
})();
I created a new angular2 app using the angularCLI (just so you know my directory structure).
Running ng serve puts all my files in the dist folder and runs the hello world app in the browser with no issue.
I'm trying to run the same app in electron, but it is unable to find all the vendor files (including #angular) since it uses the file protocol in a script src:
This
<script src="vendor/es6-shim/es6-shim.js"></script>
<script src="vendor/reflect-metadata/Reflect.js"></script>
<script src="vendor/systemjs/dist/system.src.js"></script>
<script src="vendor/zone.js/dist/zone.js"></script>
produces this
file:///vendor/es6-shim/es6-shim.js Failed to load resource: net::ERR_FILE_NOT_FOUND
file:///vendor/reflect-metadata/Reflect.js Failed to load resource: net::ERR_FILE_NOT_FOUND
file:///vendor/systemjs/dist/system.src.js Failed to load resource: net::ERR_FILE_NOT_FOUND
file:///vendor/zone.js/dist/zone.js Failed to load resource: net::ERR_FILE_NOT_FOUND
How do you prepend the correct path in the file: protocol that electron uses?
My gulpfile.js:
var gulp = require('gulp'),
del = require('del'),
runSeq = require('run-sequence');
gulp.task('clean-electron', function(){
return del('dist/electron-package/**/*', {force: true});
});
gulp.task('copy:electron-manifest', function(){
return gulp.src('./package.json')
.pipe(gulp.dest('./dist/electron-package'))
});
gulp.task('copy:electron-scripts', function(){
return gulp.src('./src/electron_main.js')
.pipe(gulp.dest('./dist/electron-package'));
});
gulp.task('copy:vendor-for-electron', function() {
return gulp.src('./dist/vendor/**/*')
.pipe(gulp.dest('./dist/electron-package/vendor'))
});
gulp.task('copy:spa-for-electron', function(){
return gulp.src(["./dist/*.*", "./dist/app/**/*"])
.pipe(gulp.dest('dist/electron-package'));
});
gulp.task('electron', function(done){
return runSeq('clean-electron', ['copy:spa-for-electron', 'copy:vendor-for-electron', 'copy:electron-manifest', 'copy:electron-scripts' ], done);
});
The closest I got was doing this:
my index.html:
<script src="vendor/es6-shim/es6-shim.js"></script>
<script src="vendor/reflect-metadata/Reflect.js"></script>
<script src="vendor/systemjs/dist/system.src.js"></script>
<script src="vendor/zone.js/dist/zone.js"></script>
<script>
console.log("In my script tag:");
var systemConfigPath = 'system-config.js';
var mainPath = 'main.js';
if (window.location.protocol == "file:"){
require(__dirname + '/vendor/es6-shim/es6-shim.js');
require(__dirname + '/vendor/reflect-metadata/Reflect.js');
require(__dirname + '/vendor/systemjs/dist/system.src.js');
require(__dirname + '/vendor/zone.js/dist/zone.js');
systemConfigPath = __dirname + '/' + systemConfigPath;
mainPath = __dirname + '/' + mainPath ;
}
System.import(systemConfigPath).then(function () {
System.import(mainPath);
}).catch(console.error.bind(console));
but that still gives me issues as the vendor files reference other files inside the same directories:
Edit:
I am now trying to use webpack to build my electron app (with no success).
I also created a github repo if you would like to see the code.
From How should I configure the base href for Angular 2 when using Electron? the answer is to change you
<base href="/">
to
<base href="./">
Okay! so I am not sure it's the best answer, as it still produces some silly errors, but here we go...
My index.html now looks like this:
<body>
<electron-angular-boilerplate-app>Loading...</electron-angular-boilerplate-app>
<!--will give errors in electron... oh well-->
<script src="vendor/es6-shim/es6-shim.js"></script>
<script src="vendor/reflect-metadata/Reflect.js"></script>
<script src="vendor/systemjs/dist/system.src.js"></script>
<script src="vendor/zone.js/dist/zone.js"></script>
<script>
// if require is defined, we are on node / electron:
if (!(typeof(require) == "undefined")){
require('./vendor/es6-shim/es6-shim.js');
require("./vendor/reflect-metadata/Reflect.js");
require("./vendor/systemjs/dist/system.src.js");
require("./vendor/zone.js/dist/zone.js");
require("./system-config.js");
require("./main.js");
} else {
System.import('system-config.js').then(function () {
System.import('main');
}).catch(console.error.bind(console));
}
</script>
</body>
This allows both my angular cli application to run and my electron app to run. The <script src=... tags still produce errors in electron as it is not able to find them. I also had to remove the System.import line from electron, so hopefully that doesn't cause any issues later on.
and to run it, we just need to make sure that the app is built and run electron in the ./dist folder:
ng build && electron ./dist
Here is the branch with my working code:
https://github.com/jdell64/electronAngularBoilerplate/tree/so-37447020-answer
I am using the gulp for run my angular app. But I am facing a problem here.
all bower_components files are copied in dest ans bower_components folder
my js files ( say 2 ) I am getting 2 js files in dest folder
same things happening for html and css files too.
What i requires is :
dest file should have only one html and js and css all or minified with source map included.( if necessary )
Basically, the gulp need to collect the files, what just i have used in the app instead of collecting from the folder as .js.
How to do this?
here is my current gulp code :
// gulp
var gulp = require('gulp');
// plugins
var connect = require('gulp-connect');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var minifyCSS = require('gulp-minify-css');
var clean = require('gulp-clean');
var runSequence = require('run-sequence');
// tasks
gulp.task('lint', function() {
gulp.src(['./app/**/*.js', '!./app/bower_components/**'])
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(jshint.reporter('fail'));
});
gulp.task('clean', function() {
gulp.src('./dist/*')
.pipe(clean({force: true}));
});
gulp.task('minify-css', function() {
var opts = {comments:true,spare:true};
gulp.src(['./app/**/*.css', '!./app/bower_components/**'])
.pipe(minifyCSS(opts))
.pipe(gulp.dest('./dist/'))
});
gulp.task('minify-js', function() {
gulp.src(['./app/**/*.js', '!./app/bower_components/**'])
.pipe(uglify({
// inSourceMap:
// outSourceMap: "app.js.map"
}))
.pipe(gulp.dest('./dist/'))
});
gulp.task('copy-bower-components', function () {
gulp.src('./app/bower_components/**')
.pipe(gulp.dest('dist/bower_components'));
});
gulp.task('copy-html-files', function () {
gulp.src('./app/**/*.html')
.pipe(gulp.dest('dist/'));
});
gulp.task('connect', function () {
connect.server({
root: 'app/',
port: 8888
});
});
gulp.task('connectDist', function () {
connect.server({
root: 'dist/',
port: 9999
});
});
// default task
gulp.task('default',
['lint', 'connect']
);
gulp.task('build', function() {
runSequence(
['clean'],
['lint', 'minify-css', 'minify-js', 'copy-html-files', 'copy-bower-components', 'connectDist']
);
});
You should make use of the gulp-useref module, which parses the build blocks in the HTML, replace them and pass those files through.
Here the example setup:
index.html:
<!doctype html>
<html ng-app="app">
<head>
<!-- build:js app.js -->
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="myscript.js"></script>
<!-- endbuild -->
</head>
<body>
Hello world!
</body>
</html>
gulpfile.js:
var gulp = require('gulp');
var useref = require('gulp-useref');
gulp.task('default', function () {
return gulp.src('app/index.html')
.pipe(useref())
.pipe(gulp.dest('dist'));
});
Running the gulp now will result in having the two files in the dist folder:
index.html - having the build block replaced by the only script tag, <script src="app.js"></script>
app.js - the concatenation of the files listed in the build block of the original index.html file
The same can be done with the css files as well.
This way you will have no extra files in your dest folder, just what you have used in your app.
var concat = require("gulp-concat");
gulp.task('minify-js', function() {
gulp.src(['./app/**/*.js', '!./app/bower_components/**'])
.pipe(uglify({
output: {
beautify: false
},
outSourceMap: true,
properties : true,
mangle:false
}))
.pipe(concat('bundle.js'))
.pipe(gulp.dest('./dist/'))
});
this will concatenate all files in one bundle.js file.