AngularJS - "import" different JS files from HTML - html

I was trying to import certain script depending on which URL I'm.
Simple <script> tag in my HTML is:
<html ng-app="myApp">
...
<script type="text/javascript" src="{{srcRoute}}" language="JavaScript"></script>
...
</html>
I was trying to get this after main module "myApp", in a run block:
angular.module('myApp', [])
.config(function($routeProvider) {
$routeProvider.
when('/', {controller: MyController, templateUrl: 'partials/home.html'}).
otherwise({redirectTo: '/'});
})
.run(function($rootScope) {
$rootScope.srcRoute = 'some/route/here.js';
});
but when running this I get something like:
GET myRoute/%7B%7BsrcRoute%7D%7D 404 (Not Found)
What I want to do is add a conditional sentence in the run block to decide which route to use. Is there a way to do this?
Thanks!

Related

Angular fails to bind expression

I am trying to build a simple web app that communicates with an external API , for the first step i wish to check if my controller,service-html integration is all in placed , so I'm tying to bind a simple variable from the controller to the view, but i am getting {{msg}} instead of a successful bind.
please ignore the service for now its just my fundumentals for later on.
main.html :
<!DOCTYPE html>
<html >
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="controller.js"></script>
<head></head>
<body ng-app="queueApi" ng-controller="MainController">
<div>
<h1>{{msg}}</h1>
</div>
</body>
</html>
queueservice.js
angular.module('queueApi')
.factory('queueService', function ($resource){
return $resource('http://127.0.0.1:8080/queue/:id',{id: '#id'});
});
controller.js
var app = angular.module('queueApi' , ['ngResource']);
app.controller('MainController', function($scope,$http, queueService){
$scope.msg = "Hi tom";
// $scope.items = queueService.query({id:2}); //getting all from id 2
});
If you look at your console you can see the error in module creation. It is because the ngResource module is in external source file rather than angular.min.js. Add also the angular-resource.js.
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-resource.min.js"></script>
<script src="controller.js"></script>
In addition to Hamlet Hakobyan's answer, you must ensure that your modules have been included in correct order. With your code structure controller.js should precede queueservice.js.
From the documentation:
Beware that using angular.module('myModule', []) will create the module myModule and overwrite any existing module named myModule. Use angular.module('myModule') to retrieve an existing module.

Angular loads HTML index instead of ng-app.js on refresh

I am playing around with adding in an Angular-UI router which is working perfectly when I click on links within my application. For example, if I go from / to /feed/9 it will load in the /partials/post.html file into the ui-view div and I can then use the '9' held in $stateParams to populate the template with the data from post 9. However if I refresh the page, the site breaks and Angular tries to load index.html as the ng-app.js file? I have no idea what is happening here. I've uploaded some screenshots to demonstrate this and I've included my node server, angular routing and the relevant html partials. I have no idea where this is going wrong so I can provide any additional data and any help would be greatly appreciated!
Working fine when coming from another link on '/'
On refresh!!
Node - server.js
var = /* Dependencies and vars */;
mongoose.connect(dbConfig.url, dbConfig.options);
app.use(express.static(__dirname + '/public'));
app.use(morgan('dev'));
app.use(bodyParser());
app.use(flash());
require('./routes/api.js')(app); //For CRUD operations on the database
require('./routes/api_proc.js')(app); //Protected endpoints for CDN
require('./routes/api_ext.js')(app); //For getting data from GCal, fb, Twitter and Instagram
/* The following code is a url rewrite to pass all
further get requests that aren't defined in the
above routing files through the index page and
hence through the Angular 'frontend' routes */
app.use(function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
app.listen(port);
Angular ng-app.js
var app = angular.module('app', ['ui.bootstrap', 'ngResource', 'ui.router']);
//Using state ui-router
// ROUTES
app.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url : '/',
templateUrl : 'partials/home.html'
})
/* ... */
.state('feed', {
url : '/feed',
templateUrl : 'partials/feed.html'
})
.state('post', {
url : '/feed/{id:.*}',
templateUrl : 'partials/post.html',
controller: 'postController'
})
$locationProvider.html5Mode(true);
});
app.factory("Feed", function($resource) {
return $resource("/api/feed/:id", {}, {
query: {
isArray: true
}
});
});
app.controller("postController", function($scope, Feed, $stateParams) {
var feed = Feed.query();
feed.$promise.then(function(promiseData) {
postArray = promiseData.slice(0,promiseData.length);
$scope.feed = promiseData;
$scope.id = $stateParams.id;
});
});
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<!-- CDN -->
<!-- Angular, Bootstrap, Angular modules, etc. -->
<!-- Styles -->
<!-- Angular Script import -->
<script type="text/javascript" src="ng-app.js"></script>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<nav><!--Bootstrap nav--></nav>
<div ui-view></div>
<footer></footer>
<script>
//For Bootstrap tooltips which are in some of the partials.
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
$('[rel=tooltip]').tooltip();
});
</script>
</body>
</html>
/partials/post.html
<div class="container-fluid main-content">
<header class="banner" class="row">
<h1 class="page-title">{{id}}</h1>
</header>
<!-- Main page info -->
</div>
I think you have relative paths pointing to your css files.
When you load page from /feed/9 then links are invalid.
Maybe it happens also for templates referenced from angular.

Links to a box within the page

I usually see in some sites a vertical navigation menu and these link are applied to a box in the page but not <iframe> tag.
can anyone help.
and thank you
I think you try to telling a loading divs without refresing the page. We call it as Single page application like Gmail. You can done this by several way.
Do this manually by calling ajex and load divs from host. All events handle by separate JS function.
Try frameworks.
*Backend frameworks like struct2 comes with this capability so this method you have to code in backend
*Frontend frameworks like angularjs support route functionality can achive this result. So you have to deal with JS in front end this time.
Example in angular js
var app = angular.module( "myApp", [] );
app.config( function ( $routeProvider ) {
$routeProvider
.when( '/this', { templateUrl: 'this.html' } )
.when( '/that', { templateUrl: 'that.html' } )
.when( '/other', { templateUrl: 'other.html' } )
.otherwise( { redirectTo: '/this' } );
});
app.controller( 'MainCtrl', function ( $scope ) {
});
<script type="text/ng-template" id="this.html">
This Page.
</script>
<script type="text/ng-template" id="that.html">
That Page.
</script>
<script type="text/ng-template" id="other.html">
Other Page.
</script>
<div ng-controller="MainCtrl">
<ul>
<li>This</li>
<li>That</li>
<li>Other</li>
</ul>
<ng-view></ng-view>
</div>
j fiddle code>> http://jsfiddle.net/joshdmiller/NEuJ6/

Issue with html5Mode in angularjs

I'm trying to remove index.html of the url using html5Mode(true) in angularjs, this is the code:
angular.module('myApp', [
'ngRoute',
'myApp.filters',
'myApp.services',
'myApp.directives',
'myApp.controllers'
]).
config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/home', {templateUrl: 'views/home.html'});
$routeProvider.when('/about', {templateUrl: 'views/about.html'});
$routeProvider.otherwise({redirectTo: '/'});
}]);
If I dont write $locationProvider.html5Mode(true); the url shows:
localhost:(port)/MyApplication/index.html
If I write $locationProvider.html5Mode(true); the url shows:
localhost:(port)
MyApplication is removed of the url.
And I want the url shows:
localhost:(port)/MyApplication/
What I'm doing wrong? What's the problem?
UPDATE:
How should show my <a> tags? Right now I have:
<a href="#/about">About</>
When I click on the link, the url shows:
localhost:(port)/MyApplication/index.html#/about
I'm lost with this.
Thanks in advance!
If your application runs under /MyApplication/ try to set the base path in your index.html and switch on html5Mode:
<html>
<head>
<base href="/MyApplication/index.html" />
...
See Using $location.

Angularjs: Multiples partials in single html?

Is possible retrieve multiples html partials in one single html? I've the next situation:
Template: {header} {main} {footer}
/index: header:"Welcome" main:"welcome text" footer:""
/help: header:"Help title" main:"faq tips" footer"Back to home"
using ng-include I've to retreive 6 html from server. If I will retrive multiples partials in one html then I will retrieve 2 html from server only, one for /index and one for /help.
This situation is a small example the real situation.
The tag script with type ng-template don't work for me, because the script must be include before of ng-include.
Thanks!
Update 04/07/12:
I seek to update more than one div at a time, with an unique html retreive. I don't like this:
function IndexCtrl($scope) {
$scope.mainPage = 'partials/index/index.html';
$scope.headerTemplate = 'partials/index/header.html';
$scope.footerTemplate = 'partials/index/footer.html';
}
After in the template use ng-includes for include these partials. I think that this is not the correct way. There is other way?
Thanks!
Templates can be embedded in the main html. For example, with the following index.html:
<!DOCTYPE html>
<html ng-app=app>
<meta charset=utf-8>
<title>App</title>
<ng-view>Loading...</ng-view>
<script type=text/ng-template id=partial1.html>
<p>foo = {{foo}}</p>
</script>
<script type=text/ng-template id=partial2.html>
<p>Contents of partial2.html</p>
</script>
<script src=app.js></script>
you can use the following app.js:
angular.module('app', [], ['$routeProvider', '$controllerProvider', function($routeProvider, $controllerProvider) {
$routeProvider.when('/p1', { templateUrl: 'partial1.html', controller: 'Partial1' });
$controllerProvider.register('Partial1', ['$scope', function($scope) {
$scope.foo = 'bar';
}]);
}]);
The documentation for the $templateCache service has more details.
What I do is use template instead of templateUrl, and use the requirejs text plugin to load the templates. that way for development you can have thousands of files for your templates, but once you minify you only have one javascript file with all the templates inlined.
I created an open source project which is setup for backbone but can easily be modified for angular which does the minification and requirejs text plugin wiring for you: http://github.com/davidjnelson/agilejs