I'm learning angularjs and there is one aspect of it that I'm struggling to understand.
My desired/expected behavior of the code below is:
User clicks the Paris link (anchor tag)
The routeProvider intercepts the request, loads the paris.html page into the ng-view.
The 'getCity' function in the controller gets the data and sets the scope variables, which are displayed in the london.html expressions.
However, I can't figure out how to config angularjs to use the 'getCity' function when the html page is loaded into the ng-view. The closest I can get is calling the 'getCity' function from within the CityController itself, bit this seems to have the undesired effect of calling the function when the whole app (index.html) is loaded instead of only when the link is clicked. The controller will have a number of different functions.
I also know you can use ng-click to call a controller's function, but I'm unsure how this would work with loading a html page into an ng-view through the route provider.
Any help would be appreciated. Please see code below from a small app built for learning purposes:
index.html
<!DOCTYPE html>
<html ng-app="mainApp">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-route.js"></script>
</head>
<body>
<ol>
<li>Paris</li>
</ol>
<div class="content-wrapper" ng-controller="CityController">
<div ng-view></div>
</div>
<script src="resources/js/app.js"></script>
<script src="resources/js/CityController.js"></script>
</body>
</html>
app.js
var app = angular.module("mainApp", [ 'ngRoute' ]);
app.config([ '$routeProvider', function($routeProvider) {
$routeProvider.
when('/cities/paris', {
templateUrl : 'resources/paris.html',
controller : 'CityController'
}).
otherwise({
redirectTo : ''
});
} ]);
CityController.js
app.controller('CityController', function($scope, $http) {
$scope.getCity = function() {
$http.get('city')
.success(function(response) {
$scope.name = response.name;
$scope.country = response.country;
}).error(function() {
//Output error to console
});
};
//$scope.getCity();
});
I don't want to call getCity here because it means the http get request to
the 'city' endpoint is called when index.html is loaded
paris.html
This is Paris.
<br><br><br>
Name: {{name}}<br>
Country: {{country}}
<br><br><br>
I think what you are looking for is the router resolve option.
A resolve contains one or more promises that must resolve successfully before the route will change. This means you can wait for data to become available before showing a view, and simplify the initialization of the model inside a controller because the initial data is given to the controller instead of the controller needing to go out and fetch the data.
Check the explanation and usage here
You can call getCity() from paris.html using ,ng-init=getCity() ,ng-init will call your function as soon as paris.html is loaded into your ng-view .
For Eg.
This is Paris.
<br><br><br>
<div ng-init=getCity() >
Name: {{name}}<br>
Country: {{country}}
</div>
<br><br><br>
Related
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'm using ngRoute to do the routing of my AngularJS application (myApp) but I have a problem: I don't know how to NOT APPLY my index.html design (with all my sidebars) to my login.html page, which seems to be applied by default if it is defined as a view. I want a simple design for my login.html page: only two fields to fill out, without the design of my index.html, which is applied to all the views in myApp. Thereby, I don't know how to do my routing to accomplish such task. Thank you very much.
<-- This is a sample of how I do my routing in myApp (for only one view - "/view1") -->
Sample of app.js:
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute',
'ngResource',
'ui.bootstrap',
'ngCookies',
'myApp.view1',
])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
For each view there is a .js file associated where I defined its routing and controllers. For instance, for view "/view1" - view1.js:
'use strict';
angular.module('myApp.view1', ['ngRoute', 'ngResource'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1.html',
controller: 'View1Ctrl'
});
}])
.controller('View1Ctrl', ['$scope', function($scope) {
// something
}]);
And a sample of my index.html:
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<script src="view1.js"></script>
<-- MORE SCRIPTS ARE LOADED -->
</head>
<body class="hamburg" ng-controller="MasterCtrl">
<-- SIDEBARS ARE DEFINED -->
<div id="content-wrapper">
<div class="page-content">
<!-- Main Content -->
<div class="row">
<div class="col-xs-12">
<div class="widget">
<div class="widget-body">
<div ng-view></div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
Given the situation above looks like you want two page layout (page design or page template), the first one is now used in index.html, and the second one you want to use in login.html which just has two fields to fill out. So angular-ui/ui-router (doc url: https://github.com/angular-ui/ui-router/wiki) could be the solution to this issue.
The idea behind that is ui-router has a very powerful tool named ui-view which you can see it as a layout or template. So when the path is on any page other than login page like /index or /home use one ui-view, and on /login page then use another different ui-view.
For a rough example:
index.html page:
<html>
<head></head>
<body>
<div ui-view="layout"></div>
</body>
</html>
I assume you will reuse the head part, so just wrap every thing from the body in the original index.html and put into the new index.html. Same to the login page login.html.
config file:
$stateProvider
.state('index', {
url: '/index',
views: {
layout: {
templateUrl: "/path/to/index.html"
}
},
controller: 'indexController'
}
.state('login', {
url: '/login',
views: {
layout: {
templateUrl: "/path/to/login.html"
}
},
controller: 'loginController'
})
So what does the code above do is very similar to what you did with $routeProvider, it defines on which url use which controller and to load which view.
Hope this can help you, if any question let me know please.
You need to create your login page as a diferente ngApp, store your sesion on the localSotarge in case of a successfull login and then redirect to you main ngApp.
In your main ngApp, validate if a session exists in the localStorage and redirecto to the loginApp if it dont.
I know it sounds a bit like overdoing stuff, but I have not found any other solution in my 3 years working with AngularJS. Now, keep in mind that this is necesary because you need to NOT TO APPLY your index.html, and the only way to do that is using another ngApp.
Routing is used for injecting views in angular SPA. What I get from from your question is you need a login dialog.
For that you may look ngDialog or uibDialog
In your case you need to load new layout. I understand, for login and for application there is mostly different layout. This operation is equal to redirecting page to new location. With new angular app and controllers for login. You can use:
$window.location.href="new/layout/template".
Read more # Angular Dev Docs.
I have index.html file which have these following below codes. I want to show result to other view searchResult.html when submitting the form. I retrieve the form data in homeCtrl but i can't do when submitting the form show the retrieved data to searchResult.html page. Please help me.
<!DOCTYPE html>
<html ng-app="myApp">
<head>
//head code...
</head>
<body ng-controller="homeCtrl">
<form ng-submit="doSearch()">
<input type="search" placeholder="From" ng-model="search.from">
<input type="search" placeholder="Destination" ng-model="search.to">
<button type="submit">Search</button>
</form>
<div ng-view></div>
</body>
</html>
var app = angular.module('myApp', [])
app.controller('homeCtrl', function($scope, $location) {
$scope.doSearch = function() {
$scope.search={};
$scope.search=$scope.search;
//retrieved data here
}
});
You can get the data in homeCtrl and store it in rootscope or localstorage then redirect page to search page and retrieve data from rootscope or localstorage to searchCtrl scope.
It may be tempting to pass data around through the $rootScope, but this is problematic. To start, your data is now bound to the root scope, and can’t be moved off into isolation. Not only is this harder to test, but it can’t be used through multiple applications if need be.
take out your Searching logic in Separate Service.
use ui-router for URL routing.
Following links will be helpful!
navigation with routing -part1
navigation with routing -part2
I am new to AngularJS and I am trying to understand it by studying sample codes.
Here I have one about $http.get, from the following link:
http://www.w3schools.com/angular/tryit.asp?filename=try_ng_customers_json
I just replaced url with one of my own but it did not work, and I am really confused, please help, thanks!
=========================
second edit: thanks to the answers, double ng-app is a mistake, but it is not the main reason for this problem. I think it has something to do with cross-site blocking, but I have turn it off on my API (I use codeigniter REST API and I set $config['csrf_protection'] = FALSE; ), I am not sure how to configure it.
<!DOCTYPE html>
<html>
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="customersCtrl">
<ul>
{{names}}
</ul>
</div>
<div ng-controller="myCtrl">
<ul>
{{names}}
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.w3schools.com/website/Customers_JSON.php")
.success(function (response) {$scope.names = response;});
});
app.controller('myCtrl', function($scope, $http) {
$http.get("https://manage.pineconetassel.com/index.php/api/v1/colors2.php")
.success(function (response) {$scope.names = response;});
});
</script>
</body>
</html>
The problem is that you have two "myApp" declarations.
From AngularJS documentation:
Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application.
So, you should move the ng-app="myApp" to the body element.
However, once you've done that you probably still won't see any result because you are cross-site scripting and browsers will (by default) block the second request.
Two ng-app directive on single page will execute the first one, 2nd one will get ignored.
Remove ng-app="myApp" from both div of your html and use angular.bootstrap to bootstrap angular app on html page using below code.
Code
angular.element(document).ready(function() {
angular.bootstrap(document, ['myApp']);
});
I have particular problem with making dropzonejs working with ng-view directive:
Below is my index.html:
<!DOCTYPE html>
<html lang="en" ng-app="Museum">
<meta charset="utf-8">
<title>Login page</title>
<link rel="stylesheet" href="framework/bootstrap-3.2.0/css/bootstrap.css">
<script src="framework/angular-1.3.0-beta.19/angular.js"></script>
<script src="framework/angular-1.3.0-beta.19/angular-resource.js"></script>
<script src="framework/angular-1.3.0-beta.19/angular-route.js"></script>
<script src="framework/angularUI-0.11.0/ui-bootstrap-tpls-0.11.0.js"></script>
<script src="framework/dropzone-3.10.2/dropzone.min.js"></script>
<link rel="stylesheet" href="framework/dropzone-3.10.2/css/dropzone.css">
<link rel="stylesheet" href="app.css">
<script src="app.js"></script>
<body>
<div ng-view></div>
</body>
</html>
My app.js:
var app = angular.module('Museum', ['ui.bootstrap', 'ngResource', 'ngRoute']).config(['$resourceProvider', function ($resourceProvider) {
// Don't strip trailing slashes from calculated URLs
$resourceProvider.defaults.stripTrailingSlashes = false;
}]).config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/login', {
templateUrl: 'components/login/login.html',
controller: 'Login',
css: 'components/login/css/login.css'
})
.when('/create', {
templateUrl: 'components/inventory/create.html',
controller: 'Add'
}
);
}]);
And my create.html page with dropzonejs:
<form action="/upload" class="dropzone" id="file-dropzone"></form>
It all works fine when I put dropzone form directly in index.html but when I route to create.html with dropzonjs using ng-view directive it does now work. Dropzone form is not process, e.g class is not "dropzone ng-pristine ng-valid dz-clickable" but "dropzone ng-pristine ng-valid", no div with message is added, etc.
Anyone has any idea?
Couldn't get the drop in method to work nicely, and indeed. it seems its only when there is a view involved.
Make sure that dropzone.js is loaded, and that the area/div you are dropping onto has an id.
on my view, I have an ng-init="initDropZone()" attribute. doesn't matter where really, just has to be in the view template.
Then, in my controller :
var myDropzone = new Dropzone("#my-dropzone",{url:'/myuploadscript.php', createImageThumbnails:false});
//I have used a success event so i can use the result from the save.
myDropzone.on("success", function(file,response) {
//remove the thumbnail that gets chucked on the dropzone element
myDropzone.removeAllFiles(true);
//result is treated as a string, I've responded in json from my
//upload script on the server.
//{success:true, newfile:'myfilepath.jpg'}
result = JSON.parse(response);
if (result.success)
{
//I originally tried using the angular ng-src bound var,
//shown as model.data.Image (using model instead of $scope)
model.data.Image = "//:0";
model.data.Image = result.newFile;
//but this was outright ignored. like no change.
//accepted defeat and just jqlite hacking to manually change
//the source of the img element.
$('#mainImg').attr("src", "/" + result.newFile);
}
});
This will change the image source immediately once the file has been uploaded and the server responds. I wish angular was more friendly and someone will no doubt point out a better solution, so if this gets a response out of a guru then we both win. otherwise, this will do as you are trying to do.
Oh and just confirming, there is no dropzone class/element defined on the html, its just a div that has an id of my-dropzone