AngularJS dynamically load template and js file - javascript

I want to dynamically add menu JavaScript file and html to content.html, but it can't do.
I created simple example
demo
I try move "<script src="menu.js"></script>" to menu.html

Your code moves away from the whole idea of writing single page app with angular. I have updated it to give you basic idea of how you would do the routes and share templates and use controller.
Check out the plunkr
html
<html>
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="menu.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
<script data-require="ui-router#*" data-semver="0.2.15" src="https://cdn.rawgit.com/angular-ui/ui-router/805e69bae319e922e4d3265b7ef565058aaff850/release/angular-ui-router.js"></script>
<script src="menu.js"></script>
<script src="index.js"></script>
</head>
<body>
<div id="menu" ng-include="'menu.html'"></div>
<div ui-view></div>
</body>
</html>
js
angular.element(document).ready(function() {
angular.bootstrap(document, ["app"]);
});
angular.module('app',['moduleContent', 'moduleMenu', 'ui.router']);
var app = angular.module('app');
app.config(function($stateProvider) {
$stateProvider
.state('index', {
url: "",
templateUrl: "first.html",
controller: 'firstCtrl'
})
.state('second', {
url: "/second",
templateUrl: "second.html"
})
});
app.controller('firstCtrl', ['$scope', function($scope) {
$scope.page = "first";
}]);
//Conttent module
angular.module('moduleContent',[])
.controller('contentCtrl', contentCtrl);
function contentCtrl(shareData)
{
shareData.currentPage = 0;
}

Related

In AngularJS, loaded content by ui-view cannot read javascript file in parent content

I want to insert header and nav bar into index.html
When header and nav bar are in index.html, My app works well.
but seperate these files to html and try to load, ui-view do not load script files.
So logout function does not work when ui-view loaed header.html
On the other hand, css works well.
I tried to follow answers like
Angularjs does not load scripts within ng-view
or
html partial is not loaded into ui-view
but it did not help to fix my problem..
Why this situation occurred?
Please any handsome or pretty developer help me..
These are my code.
app.js
'use strict';
var mainApp = angular
.module('adminApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'ui.router'
]);
mainApp.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/admin/login');
$stateProvider
.state('root',{
url: '',
abstract: true,
views: {
'headerContainer': {
templateUrl: 'views/header.html',
controller: 'HeaderCtrl',
controllerAs: 'header'
},
'navContainer':{
templateUrl: 'views/nav.html',
controller: 'NavCtrl',
controllerAs: 'nav'
}
}
})
.state('root.login', {
...
})
});
index.html
<!DOCTYPE html>
<html ng-app="adminApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Admin</title>
<base href="/">
<!-- CSS-->
<link href="bower_components/bootstrap/dist/css/main.css" rel="stylesheet">
<!-- Font-icon css-->
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<!-- start: Favicon -->
<link href="favicon.ico" rel="shortcut icon">
<!-- end: Favicon -->
</head>
<body class="sidebar-mini fixed" ng-controller="AppCtrl">
<div class="wrapper">
<div ui-view="headerContainer"></div>
<div ui-view="navContainer"></div>
<div ui-view="appContainer"></div>
</div>
<!-- Javascripts-->
<script src="../bower_components/bootstrap/dist/js/jquery-2.1.4.js"></script>
<script src="../bower_components/angular/angular.js"></script>
<script src="../bower_components/bootstrap/dist/js/bootstrap.js"></script>
<script src="../bower_components/angular-animate/angular-animate.js"></script>
<script src="../bower_components/angular-cookies/angular-cookies.js"></script>
<script src="../bower_components/angular-resource/angular-resource.js"></script>
<script src="../bower_components/angular-route/angular-route.js"></script>
<script src="../bower_components/angular-sanitize/angular-sanitize.js"></script>
<script src="../bower_components/angular-touch/angular-touch.js"></script>
<script src="../bower_components/angular-ui-router/release/angular-ui-router.js"></script>
<script src="../bower_components/bootstrap/dist/js/main.js" ></script>
<script src="scripts/app.js"></script>
<script src="scripts/controllers/headerCtrl.js"></script>
<script src="scripts/controllers/navCtrl.js"></script>
</body>
</html>
header.html
<header class="main-header hidden-print">
<nav class="navbar navbar-static-top">
<div class="navbar-custom-menu">
<ul class="top-nav">
<li>
<a ng-click="logout();">Logout</a>
</li>
</ul>
</div>
</nav>
</header>
headerCtrl.js
mainApp.controller('HeaderCtrl', function ($scope, $cookieStore) {
$scope.logout = function () {
angular.forEach($cookies.getAll(), function (v, k) {
$cookies.remove(k);
}); // This is for remove all cookies
};
});
main.js
$('.top-nav li a').on('click', function (e) {
console.log('Clicked header li');
});
It seems like you haven't used controller alias while calling logout method
ng-click="header.logout();"
As #pankaj said you need to declare the logout method on your controller alias
ng-click="header.logout();"
And the same applies for your js. You have to reference logout with this keyword since you are using controller as syntax
mainApp.controller('HeaderCtrl', function ($scope, $cookieStore) {
var vm =this;
vm.logout = function () {
angular.forEach($cookies.getAll(), function (v, k) {
$cookies.remove(k);
}); // This is for remove all cookies
};
});
For more Info: AngularJs "controller as" syntax - clarification?

How create routes in AngularJS + JavaScript?

I'm creating a website and I'm using JavaScript + AngularJS, presently I create the routes for the application, but it always returns 404 not found on the server, I've tried several examples of the internet but none of them worked, here's an example of my code, remembering that The html pages are inside the WebContent:
<html ng-app="angularRoutingApp">
<head>
<title>Home</title>
<meta charset="utf-8">
</head>
<body>
<div>
index <br> home
</div>
<div ng-view></div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.3/angular-route.js"></script>
<script>
var angularRoutingApp = angular.module('angularRoutingApp', ['ngRoute']);
angularRoutingApp.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when("/index", {
template: "/index.html"
})
.otherwise({
redirectTo: '/home.html'
});
});
</script>
</body>
</html>
you forgot the ng-view directive.
also,
the href need to be with a hash prefix - or using the Link directive.
the redirectTo key need to provide a view [name/address] & not a
template
if you want to use template files & not inline code use the templateUrl key
you can see an example of your code here: http://codepen.io/AceDesigns/pen/ZLXLKa
<html ng-app="angularRoutingApp">
<head>
<title>Home</title>
<meta charset="utf-8">
</head>
<body>
<div>
index<br>
home
</div>
<div class="">
<ng-view></ng-view>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.3/angular-route.js"></script>
<script>
var angularRoutingApp = angular.module('angularRoutingApp', ['ngRoute']);
angularRoutingApp.config(function($routeProvider){
$routeProvider
.when("/index", {template:"<div>INDEX VIEW</div>"})
.when("/home", {template:"<div>HOME VIEW</div>"})
.when("/tempFile", {templateUrl: "views/temp_file.html"})
.otherwise({redirectTo: '/home'});
});
</script>
</body>
</html>

AngularJs with prettyprint ngView Routing issue

I am using "prettyprint" along with "AngularJs" which is working very well, but only issue is if I use routing, then the prettyprint function is not working (as it might have been configured to run on pageLoad). Now, what if I am going to various ng-view pages and coming back? How to run the prettyprint function even on route change?
HTML:
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.min.css">
<link rel="stylesheet" href="https://cdn.rawgit.com/google/code-prettify/master/styles/sons-of-obsidian.css">
<script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://code.angularjs.org/1.2.1/angular-route.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/run_prettify.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
One
Two
Three
<div ng-view=""></div>
<script>
//App Declaration
var app = angular.module('myApp', ['ngRoute'] );
//Controllers
app.controller('myCtrl', function($scope) {
});
//Routers
app.config(function($routeProvider){
$routeProvider
.when('/one', {
templateUrl: 'one.html'
})
.when('/two', {
templateUrl: 'two.html'
})
.when('/three', {
templateUrl: 'three.html'
})
.otherwise({
redirectTo: '/one'
});
});
</script>
</body>
</html>
one.html
This is one
<pre class="prettyprint">
<div>
<p>
<a href="http://www.google.com">Google</a>
</p>
</div>
</pre>
two.html
This is two
Image on first time clicking 'one' link:
Going to 2nd view or 3rd view and then coming back:
Can someone help me out please?

AngularJS UI router redirect

I am trying to redirect to another page using angular redirect. But I am getting a couldn't resolve from state error. I followed the How to pass parameter when I redirect the page in angularjs using ui router? link.
Please find below my route.js code:
var helloWorldApp = angular.module('helloWorldApp', ['ui.router']);
helloWorldApp.config(function($stateProvider,$urlRouterProvider) {
$stateProvider
.state('first', {
url: '/first',
templateUrl: 'first.html'
})
.state('second', {
url: '/second',
templateUrl: 'second.html'
});
});
My first.html code
<html lang="en" ng-app="helloWorldApp">
<head>
<meta charset="UTF-8">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-animate.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.14.2.js"></script>
<script type="text/javascript" src="./app/routes.js"></script>
</head>
<script type="text/javascript">
var helloAppConf = angular.module('helloWorldApp', ['ui.router']);
helloAppConf.controller('firstCtrl',function($scope,$state){
$scope.userInput='Hello world from first page';
$scope.getNewPage=function() {
$state.go("second", { id: $scope.userInput });
}
});
</script>
<body>
<div ng-controller="firstCtrl">
<h4>{{userInput}}</h4>
<button ng-click="getNewPage()">New Page</button>
</div>
</body>
</html>
My second.html code
<!DOCTYPE html>
<html lang="en" ng-app="helloWorldApp">
<head>
<meta charset="UTF-8">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-animate.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.14.2.js"></script>
<script type="text/javascript" src="./app/routes.js"></script>
</head>
<script type="text/javascript">
var helloAppConf = angular.module('helloWorldApp', ['ui.router']);
helloAppConf.controller('secondCtrl' , function($scope, $state){
$scope.id = $stateParams.id;
});
</script>
<body>
<div ng-controller="secondCtrl">
<h4>{{id}}</h4>
<button ng-click="getNewPage()">New Page</button>
</div>
</body>
</html>
I am using springboot and my project structure snapshot is attached here:
I am able to access both first.html and second.html pages on my browser. But when I click on the New Page button on first.html, I get the
Error: Could not resolve 'second' from state ''
at Object.t.transitionTo (http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js:7:8834)
at Object.t.go (http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js:7:8182)
at Scope.$scope.getNewPage (http://localhost:8080/first.html:18:16)
at fn (eval at (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js:13322:15), :4:221)
at callback (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js:23549:17)
at Scope.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js:15989:28)
at Scope.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js:16089:25)
at HTMLButtonElement. (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js:23554:23)
at HTMLButtonElement.eventHandler (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js:3298:21)
Please help. Thanks in advance.
In your second html code you inject $state wrongly instead of $stateParams. So that your code didn't work
Inject with $stateParams
var helloAppConf = angular.module('helloWorldApp', ['ui.router']);
helloAppConf.controller('secondCtrl' , function($scope, $stateParams){
$scope.id = $stateParams.id;
});
or use $state.params.id
var helloAppConf = angular.module('helloWorldApp', ['ui.router']);
helloAppConf.controller('secondCtrl' , function($scope, $state){
$scope.id = $state.params.id;
});

Angular.js - show link depending on view

I would like to have a link back to the landing page in the header of my app's views but obviously not on the landing page itself. How would I optimally implement that in Angular.js?
Should I use $location.url() to determine the view or should I use bind-html or something else altogether?
Thanks for some tips and help!
EDIT
my current code, I thought I'd made it a little easier since each view has its own controller, however the link is always shown:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<style>
</style>
</head>
<body ng-app="myApp">
<div data-role="page" id="pageone">
<div data-role="header">
<h1>WELCOME!</h1>
BACK TO HOME
</div>
<div ng-view></div>
<div data-role="footer">
<h1>footer</h1>
</div>
</div>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js"></script>
<script>
'use strict';
var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix('!');
$routeProvider
.when('/', {
templateUrl : 'views/home.html',
controller : 'HomeController'
})
.when('/other', {
templateUrl : 'views/other.html',
controller : 'OtherController'
});
});
app.controller('HomeController', function($scope, $http, $location, $route) {
$scope.isLandingPage = true;
});
app.controller('OtherController', function($scope, $route) {
$scope.info = 'Other';
});
</script>
</body>
</html>
The link is always shown because your div in which is link doesn't have any controller attached.
You can do it this way:
app.controller('landingPageCtrl', ['$scope', '$location', function($scope, $location){
$scope.isLandingPage = function(){
return ($location.url() == '/home') ? true : false;
}
}]);
then use ng-show to hide or show link depending on location
<div ng-controller="landingPageCtrl" data-role="header">
<h1>WELCOME!</h1>
BACK TO HOME
</div>
I like to check for my route (or state in ui.router).
$scope.isLandingPage = $state.current.name === 'home';
and use <a ng-show="!isLandingPage">Link</a>

Categories