My website follow the following template:
<html lang="fr" ng-app="myApp">
<head>
<meta charset="UTF-8"><title>{{title}}</title>
</head>
<body>
<navbar>
// My menu and other links
</navbar>
<section role="main" ng-controller="car-controller">
<ul>
<li ng-repeat="car in car">
{{car.state}}
</li>
</ul>
</section>
// Footer
</body>
</html>
All my different pages should have a different main section with a different controller to manage them.
My question is : how can I update my {{title}} statment from all my controllers like the car-controller on this exemple?
You can modify the document title from inside the controllers by injecting $window or $document, without binding any value to it.
angular.module('myApp')
.controller('car-controller', function($scope, $window){
$window.document.title = "Title from Car Controller";
});
You can move the logic to a callable function if required and this can be done for all the controllers you are planning to use for each section.
Related
I have a problem. In my html file I have a following content:
<div ng-controller='nav'>
<ul >
<li ng-show="sh" >
<a ui-sref="problems">name</a>
</li>
</div>
My controller is:
app.controller('nav', function($scope, $state, $http){
$(function(){
$scope.sh=true;
//$http.get('something');
});
});
If
$http.get('something')
is commented, ng-show does not work. However, if I uncomment it, it starts to work. I cannot understand the reason of this. Did you have a similar problem?
Try this below code.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div ng-controller='nav'>
<ul>
<li ng-show="sh">
<a ui-sref="problems">name</a>
</li>
</ul>
</div>
<script src="../lib/angular.js"></script>
<script>
var app = angular.module('app', []);
app.controller('nav', function ($scope, $state, $http) {
$scope.sh = true;
$http.get('something')
});
</script>
</body>
</html>
I dont know why you included the jquery part. It is always good to not to use jquery in AngularJS projects. You will get almost all things in AngularJS one way or the another.
There is no need for jquery function there you can directly use $scope.sh=true;
I'm learning angularjs. When I learn scope, I see rootScope. But I don't really understand what it is.
For example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1>Family Name {{lastname}} Members:</h1>
<ul>
<li ng-repeat="x in names">{{x}} {{lastname}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $rootScope) {
$scope.names = ["Emil", "Tobias", "Linus"];
$rootScope.lastname = "Refsnes";
});
</script>
</body>
</html>
But I don't understand what's the difference between the following code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1>Family Name {{lastname}} Members:</h1>
<ul>
<li ng-repeat="x in names">{{x}} {{lastname}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["Emil", "Tobias", "Linus"];
$scope.lastname = "Refsnes";
});
</script>
</body>
</html>
So if there is no difference between scope and rootScope, why do we need to use rootScope?
I hope someone can give me a simple example so that I can understand rootScope easily.
I would like to add to #Yaser answer. I will use google chrome console to explain the $rootScope hierarchy which is inherited by all the scopes in the entire web page.
Step 1: Open chrome web developer tool and select the div with ng-app = "myApp"
Step 2: Goto chrome web developer tool's console and type angular.element($0).scope(), this will fetch you an object containing $rootScope details.
Here you will find a property lastname: "Refsnes"
Step 3: Goto Elements tab and select one of the <li>
Step 4: Type angular.element($0).scope() in the console, this will fetch you and object containing selected scope's details
Expand the parent property and you will find rootScope's property lastname: "Refsnes"
This should explain how $rootScope is inherited by all other scopes on the web page
Every application has a single root scope. All other scopes are descendant scopes of the root scope. Scopes provide separation between the model and the view, via a mechanism for watching the model for changes. They also provide event emission/broadcast and subscription facility.
More info here.
However a very simple explanation is consider rootScope and the original parent of all child scopes. If you imagine a hierarchy the rootScope is at the top.
I case of your example there is no rootScope involved, it is just a perent scope.
So you have a lastname in your parent scope, and since ng-repeat creates a child scope, everyone of them has a lastname as well.
The $rootScope is the top-most scope. An app can have only one $rootScope which will be shared among all the components of an app. Hence it acts like a global variable. All other $scopes are children of the $rootScope.
var app = angular.module('myApp', []);
app.controller('Ctrl1', ['$scope','$rootScope', function ($scope,$rootScope) {
$rootScope.name = "Rahul";
}]);
app.controller('Ctrl2', ['$scope','$rootScope', function ($scope,$rootScope) {
$scope.name = $rootScope.name;
}]);
<!DOCTYPE html>
<html lang="en-US" ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div>
<div ng-controller="Ctrl1">
<span>{{name}}</span> - controller -1
</div>
<hr>
<div ng-controller="Ctrl2">
<span>{{name}}</span> - controller -2
</div>
</div>
</body>
</html>
var app = angular.module('myApp',[]) [enter image description here][1] //Here rootScope is created only one time
Check structure from the link: - https://i.stack.imgur.com/rzBj3.png
Here is a simple use of rootScope as passing data from one controlleer to another
We are attempting to create a MVC/AngularJS mini-SPA site using various links found on tutorial sites and others like: AngularJS routing in MVC application with templates. However, clicking on the links appear to load the whole page every time, and the templates are never loaded. I am sure I'm missing something simple, but can't figure it out.
My _Layout.cshtml looks like:
<!DOCTYPE html>
<html ng-app="registrationModule">
<head>
<meta charset=" utf-8" />
<meta name="viewport" content="width=device-width" />
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/angular-resource.min.js"></script>
<script src="~/Scripts/angular-route.min.js"></script>
<script src="~/GrextScripts/registration-module.js"></script>
<script src="~/GrextScripts/user-repository.js"></script>
<script src="~/GrextScripts/user-controller.js"></script>
#RenderSection("SectionInHeader", required: false)
</head>
<body>
<header>
<div class=" content-wrapper">
<div class="float-left">
<p class="site-title">
GREXT
</p>
</div>
<div class="float-right">
<nav>
<ul id="menu">
<li>Home</li>
<li>Users</li>
</ul>
</nav>
</div>
</div>
</header>
#RenderBody()
#RenderSection("scripts", required: false)
</body>
</html>
The ControlPanel/Index.cshtml (the {{5+5}} renders properly as a "10" on the page, this was just to see if the AngularJS was working
#{
}
<div ng-view>
{{5+5}}
</div>
registration-module.js
var registrationModule = angular.module("registrationModule", ["ngRoute", "ngResource"])
.config(function($routeProvider, $locationProvider) {
$routeProvider.when("/ControlPanel/Users", {
templateUrl: "/templates/users/all.html",
controller: "userController"
});
$locationProvider.html5Mode(true);
});
user-controller.js
registrationModule.controller("UserController", function($scope, userRepository, $location) {
$scope.users = userRepository.get();
});
And last, the template: /templates/users/all.html
{{1+1}}
<table>
<tr><td>User Name</td></tr>
<tr ng-repeat="user in users">
<td>{{user.UserName}}</td>
</tr>
</table>
As mentioned, when I click on the Users link in the page, the whole page reloads and the template all.html is not loaded as I expect it.
#aaronfrost's comment made me re-check my javascript console more thoroughly and found that I need to include a
<base href="/" />
in the < head> tag of my document. Adding this causes everything to work.
Not sure, but the problem may be that you declared the controller as "UserController" with a capital "U", but in the routeProvider you specified it with a lowercase "u" as "userController".
I am guessing that you have an error in the console, so you might want to check there.
Change the routeProvider to use "UserController" instead of "userController" and it should work.
I am new to angularjs ,i make a sample app with custom directives now i add routing as well but it doesn't working.When i start project index file is loaded in browser that is working fine but when i click on nav bar links then about and contact page is not displayed it's remains on index.html.
here is my index.html:
<html ng-app="myApp">
<head>
<title>Reddit New World News (Task)</title>
<link href='http://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
<script src="angular/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular-route.min.js"></script>
<script src="myApp.js"></script>
<script src="myAppCtrl.js"></script>
<script src="headerDirective.js"></script>
<script src="searchDirective.js"></script>
<script src="myDataDirective.js"></script>
<!-- start menu -->
</head>
<body>
<div header-table></div>
<div class="content" ng-controller = "myAppCtrl">
<div class="container" >
<div ng-view></div>
</div>
</div>
</body>
</html>
myAppCtrl:
// TODO: Wrap in anonymous function
(function () {
var myApp = angular.module('myApp', ['ngRoute']);
// configure our routes
myApp.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'code/index.html',
controller : 'myAppCtrl'
})
// route for the about page
.when('/about', {
templateUrl : 'code/about.html',
controller : 'aboutController'
})
// route for the contact page
.when('/contact', {
templateUrl : 'code/contact.html',
controller : 'contactController'
});
});
// TODO: min-safe with bracket notation
myApp.controller('myAppCtrl', ['$scope', '$http', function($scope, $http) {
$scope.sortType = '';
$scope.sortReverse = true;
// TODO: Keep lines short - it's easier to read
$http.get("https://www.reddit.com/r/worldnews/new.json")
.success(function (response) {
$scope.stories = response.data.children;
});
}]);
myAppCtrl.controller('aboutController',function(){
// create a message to display in our view
$scope.message = 'Everyone come and see how good I look!';
});
myAppCtrl.controller('contactController', function($scope) {
$scope.message = 'Contact us! JK. This is just a demo.';
});
})();
headerDirective.html:
<div class="top-header"></div>
<div class="container">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="header">
<h1>Reddit</h1>
</div>
<div class="header-right">
<h2>World's Latest News</h2>
</div>
<div>
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
</div>
</nav>
<div class="clearfix"></div>
</div>
any guide thanks.
Like some people allready mentioned, you should deffinitly read the docs and probably watch some tutorials. I'm trying to see what you are doing, but it's not clear to me.
But I think I see where it goes wrong in your thoughts:
You have 3 'templates' index.html, about.html and contact.html. In your config You use them in your routing. By watching your files my guess is that you are expecting that, depending on the route, these html-files will be loaded. Just like when redirecting to that page.
What you should do is make a index.html with the html You use on every page. this can be the <head></head> only, but can also contain your header with navigation and footer. Then you use <ng-view></ng-view> or <div ng-view></div> where you want the templates to load in your page. These templates don't need to contain the parts you allready defined in your index.html. You have only the content in it.
So, a simple example:
index.html
<html>
<head>
//loading your scripts etc.
</head>
<body>
<ng-view></ng-view>
</body>
</html>
Than, instead of creating a template called index.html, you make a template home.html with the content:
<div class="container">
<h1>My Home</h1>
</div>
Now the contentpart from your home.html will load in your index.html where you define de ng-view.
An other thing I noticed is the path you define in templateUrl. You define the location as code/about.html. You have to give it the path from your index.html (the main html) In your case that will just be templateUrl: 'about.html'.
I would suggest putting the different files in different folders. So, one for your templates, one for your js-files (probably a js-folder with another folder in it for your js-file with directives etc.).
I hope this will help you on your way. But deffinitly read the docs and watch some tutorials. It will help you a lot.
I am designing a page in angularjs that would be a mini SPA (single page app). This page is part of a larger web site that was written in traditional jquery and asp.net. The page will have 2 main sections - the 1st section is just some simple data elements that can be bound easily with ng-model's. The 2nd section will be dynamically generated based on user's interaction, and the data will be retrieved through ajax ($http or $resource).
So should I have ng-view on the whole content page that contains the 2 sections? Or should I only do ng-view on the 2nd dynamic sections? If it's better to have ng-view on the 2nd section only, how do I handle the routes in this case knowing that the 1st section's data should be preserved statically?
thanks.
You don't have to use ng-view and routes for your simple case (widget-like angular application inside other application). You can use ng-include instead. Here is an example of application. I prefer this approach because it does not require to use shared resource like URL location hash that may be already in a use by legacy application or other widgets. Application below switch views dynamically, loads different data for each view and affects it's display options (number of displayed items):
HTML
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#*" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="angular.js#*" data-semver="1.2.11" src="http://code.angularjs.org/1.2.11/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<h1>Here is my legacy app markup</h1>
<div ng-app="app" ng-controller="appController">
<div>
<input placeholder="Number of items" ng-model="numberOfItems"/><br/>
<select placeholder="View" ng-model="currentView" ng-options="view.name for view in views"></select>
</div>
<div ng-include="currentView.url"></div>
</div>
<div id="jqueryContainer">And here is some markup generated with jQuery<br /></div>
</body>
</html>
JavaScript
angular.module('app', []).
controller('appController', function($scope, $http) {
$scope.views = [{
name: 'view1',
url: 'view1.html',
dataUrl: 'data1.json'
}, {
name: 'view2',
url: 'view2.html',
dataUrl: 'data2.json'
}];
$scope.numberOfItems = 2;
$scope.currentView = $scope.views[0];
$scope.$watch('currentView', function(currentView) {
if(currentView && currentView.dataUrl) {
$http.get(currentView.dataUrl).success(function(data) {
$scope.data = data;
});
}
});
});
$(function(){
$('#jqueryContainer').append('<span>Some markup generated dynamically.</span>');
});
view1.html
<div>
<h2>View1 specific markup {{data.length}}</h2>
<ul>
<li ng-repeat="item in data | limitTo:numberOfItems">{{item.text}}</li>
</ul>
</div>
data1.json
[{"text":"Text1"},{"text":"Text2"},{"text":"Text3"},{"text":"Text4"},{"text":"Text5"}]
Plunker: http://plnkr.co/edit/Y5IZmPbrrO63YrL8uCkc?p=preview
You can also find useful examples of this approach in AngularJS documentation: http://docs.angularjs.org/api/ng.directive:ngInclude
yes you can separate the static view with the dynamic view, in actual this is what angularjs suggest.It is not required to move the scope of ng-app.
so you can do like this: menu is displayed as the static part
index.html
<body ng-app>
<ul class="menu">
<li>view1</li>
<li>view2</li>
</ul>
<div ng-view></div>
</body>
in your config file you can include your routing which page routes to which page and which controller to used on loading of any view.
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
$routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});