I've just started learning web development on my own, and I've run into an issue where either my entire app or just a controller just won't cooperate.
In prototype.js, I declare the app:
var cds = angular.module('cds', ['ngRoute']);
cds.config(function($routeProvider) {
$routeProvider
.when('/', {
controller: 'appCtrl',
templateUrl: 'partials/login.html'
})
.otherwise({
redirectTo: '/'
});
});
cds.controller('appCtrl', ['$scope', function($scope) {
$scope.pageClass = 'page-login';
$scope.list = [
{name: 'One', description: 'I'},
{name: 'Two', description: 'II'},
{name: 'Three', description: 'III'},
{name: 'One More', description: 'Extra'}
];
}]);
In my HTML file:
<!DOCTYPE html>
<html ng-app='cds'>
<head>
<title>References</title>
<meta charset="utf-8">
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script src="js/prototype.js"></script>
<style type="text/css">
#import url("styles.css");
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="css/font-awesome.css">
</head>
<body ng-controller='appCtrl' onload="align()" onresize="align()">
{{ pageClass }}
<div ng-view></div>
<div id="dropdown">
<button class="drop-btn">Options</button>
<div class="dropdown-content">
<img src="img/header.menu.png">
</div>
</div>
</body>
</html>
For some reason, {{ pageClass }} won't even display the value I assigned to it in the controller, let alone ng-view elements. Before, I had followed a very old routing tutorial where the app was declared using just angular.module('myApp', ...), and all controllers made as individual functions independent from the angular app, and everything worked fine for me. However, after jumping from angular 1.0.7 to 1.5.8 (it's a long story, and a newbie mistake), I tried updating the style and cleaning my code up, and this is what happened. I feel like I'm missing something very basic here.
Edit:
Turns out I forgot to include ng-route. Derp. Now everything's working perfectly. Thanks all!
Looks like you're missing the ngRoute module. You can link to it through the CDN:
http://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular-route.min.js
Here's a fiddle with the added dependency.
hey be sure to include ngRoute, and maybe put the script includes at the bottom of body... got your fiddle to work by doing so
Related
I'm digging into Angular and have decided to use the Angular Material library to assist in my first application. So far I have some very basic code I copied from https://material.angularjs.org/1.1.0/demo/navBar which I have modified to fit my own needs. I'm having some trouble wrapping my head around routing and the md-nav-items.
<html>
<head>
<title>PRT - CIT</title>
<meta name="viewport" content="width=device-width, initial-scale=1" </meta>
<!-- Angular Material style sheet -->
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic"> </head>
<body ng-app="MyApp" id="bootstrap-overrides">
<div ng-controller="AppCtrl" ng-cloak="" class="navBardemoBasicUsage main">
<md-content class="md-padding">
<md-nav-bar md-selected-nav-item="currentNavItem" nav-bar-aria-label="navigation links">
<md-nav-item md-nav-click="goto('queue')" name="queue">Queue</md-nav-item>
<md-nav-item md-nav-click="goto('detail')" name="detail">Detail</md-nav-item>
<md-nav-item md-nav-click="goto('request')" name="request">Request</md-nav-item>
<!-- these require actual routing with ui-router or ng-route, so they won't work in the demo
<md-nav-item md-nav-sref="app.page4" name="page4">Page Four</md-nav-item>
<md-nav-item md-nav-href="#page5" name="page5">Page Five</md-nav-item>
--></md-nav-bar>
<div class="ext-content"> External content for `<span>{{currentNavItem}}</span>` </div>
</md-content>
</div>
<script src="node_modules/angular/angular.js"></script>
<script src="node_modules/angular-resource/angular-resource.js"></script>
<script src="node_modules/angular-animate/angular-animate.js"></script>
<script src="node_modules/angular-route/angular-route.js"></script>
<script src="node_modules/angular-aria/angular-aria.js"></script>
<script src="node_modules/angular-messages/angular-messages.js"></script>
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-114/svg-assets-cache.js"></script>
<script src="node_modules/angular-material/angular-material.js"></script>
<script src="js/site.js"></script>
<link rel="stylesheet" href="/css/site.css">
</body>
</html>
Here's my JS:
(function () {
'use strict';
var MyApp = angular.module('MyApp', ['ngMaterial', 'ngMessages', 'material.svgAssetsCache', 'ngRoute']).controller('AppCtrl', AppCtrl);
function AppCtrl($scope) {
$scope.currentNavItem = 'queue';
}
MyApp.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/index.html'
, controller: 'AppCtrl'
}).when('/queue', {
templateUrl: '/partials/queue.html'
, controller: 'AppCtrl'
}).when('/detail', {
templateUrl: '/partials/detail.html'
, controller: 'AppCtrl'
}).when('/request', {
templateUrl: '/partials/request.html'
, controller: 'AppCtrl'
});
});
})();
I'm kind of lost as to how I should route the tabs. From what I've read, md-nav-bar has some routing built in, but I've found examples utilizing ngRoute as well ui-router.
I'm also confused as to actually populate my partial views in the
<div class="ext-content"> External content for `<span>{{currentNavItem}}</span>` </div>
I tried using md-nav-href instead of md-nav-click but it just ended up redirecting me to the pages, not populating the content below my tabs/nav-bar; I rolled back the JS I had written and that part of the HTML. I've read the other questions posted in this area that I could find but none addressed rendering different partials based on nav-bar item. Any suggestions? I was thinking I could monitor currentNavItem and have the right partial render based on the value of it, but again, I'm not sure how to actually do the rendering.
Here is a Plnker that doesn't render correctly in the preview for some reason, but the code is the same as what I have locally.
Here is an image of what it looks like running locally.
Thanks in advance!
Final Edit:
S/O to #Searching for helping me get it working below. I've updated the plnker link to reflect the changes. Note it gets a little laggy due to the base append script.
ngRoute: When $route service you will need ng-view container. This will be used to load all you routed pages.
You do not have a goto() so just use simple md-nav-href tags to navigate around. The currentNavItem is set by md-selected-nav-item which is not what you need. Let's route with your setup
index.html : update your links to look like this. Use md-nav-href
<md-nav-item md-nav-href="queue" name="queue">Queue</md-nav-item>
index.html : when using html5Mode you will need base tag. Instead of manually specifying it just use the script below. Make sure you load angular.js before this script.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.js"></script>
<script type="text/javascript">
angular.element(document.getElementsByTagName('head')).append(angular.element('<base href="' + window.location.pathname + '" />'));
</script>
script : enable html5molde, why.. too many resources out there. I encourage you to lookup :)
MyApp.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true)
$routeProvider.when('/', {
templateUrl : 'index.html',
controller : 'AppCtrl'
}).when('/queue', {
templateUrl : 'queue_partial.html',//actual location will vary according to your local folder structure
controller : 'AppCtrl'
}).when('/detail', {
templateUrl : 'detail_partial.html',
controller : 'AppCtrl'
}).when('/request', {
templateUrl : 'request_partial.html',
controller : 'AppCtrl'
});
});
I have spent hours and hours searching and googling to find out why my ngRoute is not working but couldn't find the solution so i decided to come here. Here is my code::
"app.js"
angular.module("sandwichApp",["cart", "ngRoute"])
.config(['$routeProvider', function($routeProvider){
$routeProvider
.
when("/",{
templateUrl: "app/views/sandwichList.html",
controller: "SandwichListController"
}).
when("/sandwichList",{
templateUrl: "app/views/sandwichList.html"
}).
when("/checkout",{
templateUrl: "app/views/cart.html"
}).
otherwise({
redirectTo: "/app/views/sandwichList.html"
});
}]);
// for this particular code i have tried the version where the config() doesn't contain array "[]" but only the function and it also doesn't work
"sandwichListController.js"
var main = angular.module("sandwichApp", ["clientAppServiceModule"]);
main.controller("SandwichListController", function($scope, ClientAppService, cart){
$scope.original = {
sandwiches : []
}
//.... more code here. THERE IS NO PROBLEM WITH THIS CONTROLLER SO THE CODE IS NOT IMPORTANT.
);
"index.html"
<!DOCTYPE html>
<html ng-app="sandwichApp">
<head>
<meta charset="UTF-8">
<title>title</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-route.js"></script>
<!--script src="https://cdn.jsdelivr.net/angularjs/1.5.5/angular-route.min.js"></script-->
<script src="app.js"></script>
<script src="app/services/clientAppService.js"></script>
<script src="app/controllers/sandwichListController.js"></script>
<script src="app/model/cart.js"></script>
</head>
<body ng-controller="SandwichListController">
<div><strong>Heading & Cart</strong></div>
<div ng-view></div>
</body>
</html>
"sandwichList.html"
<div>
<b>Your Cart: </b>
{{totalItems}} items / {{totPrice | currency}}
<span>checkout</span>
</div>
<div>
<input type="text" ng-model="sandwichName" ng-change="filterSandwich()"/>
</div>
<div>
<h1>Sandwiches </h1>
</div>
<div ng-repeat="sandwich in workingCopy.sandwiches">
<h3 ng-click="addItemToCart(sandwich)">
<strong>{{sandwich.Name}}</strong>
<span>{{sandwich.Price | currency}}</span>
</h3>
</div>
When i load the "index.html" page, i expect the "otherwise" section of the routeer to display the "sandwichList.html" in the <div ng-view></div> section but it doesn't work. If it can't find the file, it will complain but it doesn't complain meaning that the file is at the right location. Yet it does not work.
In the sandwichList page at least if the controllers will not work, it must be able to display the <h1>Sandwiches </h1> .
My chrome console doesn't display any errors so i don't know what is causing the problem
I think it might be because you are accidentally declaring your app twice. When registering a new module in angular you provide it a second parameter which is an array of dependencies. You are doing that where you specify your routes. However, when you go to create your controller, you're code is this:
var main = angular.module("sandwichApp", ["clientAppServiceModule"]);
Angular sees the dependencies and assumes it is to create a new app. When it realizes there is already one with the same name, it overwrites it and you lose all the route stuff you setup. Try passing your "clientAppServiceModule" to the initial app definition, then just creating your controller by doing this:
angular.module("sandwichApp").controller("SandwichListController", function($scope, ClientAppService, cart){
$scope.original = {
sandwiches : []
}
//.... more code here. THERE IS NO PROBLEM WITH THIS CONTROLLER SO THE CODE IS NOT IMPORTANT.
);
Let me know if you have any questions, or if that doesn't solve it.
I have an application with 10 views and several shared components
--app
-------components
-------------home
-----------------homeController.js
-----------------homeDirective.js
-----------------home.html
.
.
.
-------shared
----------modals
------------someModal
--------------- someModalController.js
--------------- someModal.html
the components load by angular routing
(function() {
'use strict';
angular
.module('app')
.config(appConfig);
function appConfig($routeProvider) {
$routeProvider.
when("/home", { templateUrl: "app/components/home/home.html", controller: 'homeController' })............
otherwise({ redirectTo: "/home" });
}
})();
the modals used in different components , all things are worked when the main page contains all script files. for example
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body ng-app="fleetCam" ng-controller="appController">
<div id="wrapper">
<div id="page-wrapper">
<ng-view>
</ng-view>
</div>
</div>
<!-- /#wrapper -->
<!-- jQuery -->
<script src="Scripts/jquery-2.1.4.min.js"></script>
<script src="Scripts/angular.js"></script>
<script src="Scripts/angular-route.js"></script>
<script src="Scripts/ngStorage.js"></script>
<script src="appMain/app.module.js"></script>
<script src="appMain/app.routes.js"></script>
<script src="appMain/app.services.js"></script>
<script src="appMain/app.directive.js"></script>
<script src="appMain/components/home/homeController.js"></script>
<script src="appMain/components/home/aboutController.js"></script>
<script src="appMain/shared/modal/insert/insertController.js"></script>
I looking for a way to remove the last three script tags and load controller or other dependencies on the fly. I have searched a lot about lazy loading but no one works in my context especially when I add shared components.
You could use the patterns from the async section on the official angular-seed repo: https://github.com/angular/angular-seed/#loading-angular-asynchronously
https://github.com/angular/angular-seed/blob/master/app/index-async.html
this relies on the ded/script "Async JavaScript loader & dependency manager" https://github.com/ded/script.js
I'm newer to angular so I'm sorry if this is really obvious! I'm making a super basic app and right now all I want is when a user directly goes to a page it should always display the layout and the content. I am using angular's ng-route.
As of right now, if I go to localhost:8080/ it displays the layout(index.html) and content(view/home.html). If I click on the 'About' link, it goes to localhost:8080/about and displays the layout(index.html) and the correct content(view/about.html). Now if I type localhost:8080/about in my address bar, hit enter, I get a 404 error from my server's log. I'm not sure what I'm missing. Any input appreciated!
app.js
angular
.module('TestProject', ['ngRoute']);
routes.js
angular.module('TestProject')
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl : 'views/home.html'
})
.when('/about', {
templateUrl: 'views/about.html'
})
.when('/contact', {
templateUrl: 'views/contact.html'
})
.otherwise({
redirectTo: "/"
});
$locationProvider.html5Mode(true);
});
index.html
<!DOCTYPE html>
<html lang="en" ng-app="TestProject">
<head>
<meta charset="utf-8">
<title>Test!</title>
<base href="/">
<link rel="stylesheet" href="assets/styles/app.css">
</head>
<body>
<header><h1>Logo</h1></header>
<nav>
<ul class="main">
<li>
<div class="navBorder">
About
</div>
</li>
<li>
<div class="navBorder">
Contact
</div>
</li>
</ul>
</nav>
<div ng-view></div>
<script src="../bower_components/angular/angular.js"></script>
<script src="../bower_components/angular-route/angular-route.js"></script>
<script src="app.js"></script>
<script src="routes.js"></script>
</body>
</html>
I know I don't have any controllers yet, I just started this project and there's nothing there yet.
Here are how my files are organized:
My file structure is below:
/index.html
/app.js
/routes.js
/views/home.html
/views/about.html
/views/contact.html
If using AngularJS 1.3+, you need to include a notion of a <base href="" />. You can do this in your <head> tag as such
<head>
<base href="/">
...
From the docs
Before Angular 1.3 we didn't have this hard requirement and it was
easy to write apps that worked when deployed in the root context but
were broken when moved to a sub-context because in the sub-context all
absolute urls would resolve to the root context of the app. To prevent
this, use relative URLs throughout your app:
Additionally, without this <base /> tag, you can declare .html5Mode() as such... You'll need to take one of these two approaches.
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
Ahhh I figured it out, it was a problem with my server. I had not set up mod_rewrite for it to work properly. For the time being I turned off html5Mode() and everything works fine.
Hi i am trying to write a simple Angular JS program but its not working
This is my html file:
<!DOCTYPE html>
<html data-ng-app="myApp">
<head>
<title>SPA APP</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body>
<div data-ng-view=""></div>
<script src="my-module.js"></script>
<script src="my-controller.js"></script>
</body>
</html>
This is my-module.js file
var myApp=angular.module('myApp',[]);
myApp.config(function($routeProvider){
$routeProvider
.when('/',
{
controller:'myController',
templateUrl:'view1.html'
})
.when('/view2',
{
controller:'myController',
templateUrl:'view2.html'
})
.otherwise({redirectTo:'/'});
});
And this is my-controller.js file
myApp.controller('myController',function($scope){
$scope.name="varun";
});
Any help will be appericiated.
In order to use Angular router, you need to include ngRoute module, which is not shipped by default with angular.js file.
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-route.min.js"></script>
And then you need to declare dependency:
var myApp = angular.module('myApp', ['ngRoute']);
Having done this, you can use $route service in controllers, directives, etc. and $routeProvider in config section to set up routes.