NgRoute is not working in jsfiddle - javascript

I'm new to angular and I'm about to write my first hello world App in jsfiddlle.
I managed to load content by using ng-include but I still have problem with using ngRoute:
I'm getting
Cannot read property 'insertBefore' of undefined
in the following code:
HTML
<div ng-app="myApp">
1Panel
2Panel
<div ng-include src="'main.html'"><div>
<div ng-view></div>
<script type="text/ng-template" id="first_panel.html">
First Panel
</script>
<script type="text/ng-template" id="second_panel.html">
Second Panel
</script>
<script type="text/ng-template" id="main.html">
<div ng-controller="MainCtrl as mainCtrl">
Main {{mainCtrl.foo}} <br/>
<input type="text" ng-model="mainCtrl.foo"/>
<br/>
</div>
</script>
</div>
JS
var myApp = angular.module('myApp', ['ngRoute']);
var my = {};
my.MainCtrl = function() {
this.foo = 'foo';
}
my.SecondPanelCtrl = function() {
}
my.FirstPanelCtrl = function() {
}
var routeProvider = function($routeProvider) {
$routeProvider.
when('/firstPanel', {
templateUrl: 'first_panel.html',
controller: 'FirstPanelCtrl',
controllerAs: 'firstPanelCtrl'
}).
when('/secondPanel', {
templateUrl: 'second_panel.html',
controller: 'SecondPanelCtrl',
controllerAs: 'secondPanelCtrl'
}).
otherwise({redirectTo: '/firstPanel'});
};
myApp.config(routeProvider);
// register all controllers
myApp.controller('MainCtrl', my.MainCtrl);
myApp.controller('FirstPanelCtrl', my.FirstPanelCtrl);
myApp.controller('SecondPanelCtrl', my.SecondPanelCtrl);
And here is my jsfiddle:
http://jsfiddle.net/ccTd6/14/

It is an error in your HTML syntax that messes things up:
<div ng-include src="'main.html'"></div>
^
here you missed the `/`__|
Note:
At least in Chrome that I tried that, it is the browser that gets confused and removes the ngView div altogether - so it is not Angular's fault in any case.

Related

Angular giving a weird templateURL

I am trying to navigate to another page by using the selected objectID.
Angular Routing,
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider){
$routeProvider.when('/',{
controller: 'BooksController',
templateUrl: 'views/books.html'
})
.when('/books/details/:id',{
controller: 'BooksController',
templateUrl: 'views/book_details.html'
})
});
Angular Controller:
var myApp = angular.module('myApp');
myApp.controller('BooksController', ['$scope', '$http', '$location', '$routeParams', function($scope, $http, $location, $routeParams){
console.log('BooksController loaded...');
// This To get request all the books: it works fine
$scope.getBooks = function(){
$http.get('/api/books').then(function(response){
$scope.books = response.data;
});
}
// This to get request a book with specific id it works fine
$scope.getBook = function(){
var id = $routeParams.id;
$http.get('/api/books/'+id).then(function(response){
$scope.book = response.data;
});
}
}]);
And then I have this html page which work also fine accept the button in the page, this button supposed to give me a clean templateUrl to navigate to another html page but it give me weird URL:
<div class="panel panel-default" ng-init="getBooks()">
<div class="panel-heading">
<h3 class="panel-title">Latest Books</h3>
</div>
<div class="panel-body">
<div class="row">
<div ng-repeat="book in books">
<div class="col-md-6">
<div class="col-md-6">
<h4>{{book.title}}</h4>
<p>{{book.description}}</p>
<a class="btn btn-primary" href="#/books/details/{{book._id}}">View Details</a>
</div>
<div class="col-md-6">
<img class="thumbnail" src="{{book.image_url}}">
</div>
</div>
</div>
</div>
</div>
And once I press the button I'm supposed to get a clean url such as:
http://localhost:3000/#!/books/details/599701c1f3da51117535b9ab
but instead I get this url!
http://localhost:3000/#!/#%2Fbooks%2Fdetails%2F599701c1f3da51117535b9ab
Seems like you have hashprefix !, then your URL should also have ! after hash(#)
href="#!/books/details/{{book._id}}"
Since Angular 1.6 hashprefix is defaulted to !, you can disable this behavior by setting hashPrefix to ''(blank).
.config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix('');
}
]);
Its because your url is getting converted into codes. %2f means a /.
You need to have this configuration to avoid this behavior of angular
myApp.config(['$locationProvider', function($locationProvider) {
$locationProvider.hashPrefix('');
}]);
You have Prefix in url which is converting into character i.e url encoding.
So you need to fix $locationProvider's hashPrefix property by replacing its value with empty/blank string
$locationProvider.hashPrefix('');

$location.path change url but no redirecting

I want to redirect to another page by clicking a button, but when I click on a button, URL is changed, but it is not redirected, I have to refresh the page with new URL. The same is also happening when I click on link.
locationController.js
angular.module('reservationModule').controller('locationController', function($scope, $location){
$scope.setLocation = function (url) {
$location.path(url);
};
})
reservationModule.js
(function () {
var resModule = angular.module('reservationModule', ['ngRoute']);
resModule.controller('HomeController', function ($scope) { // here $scope is used for share data between view and controller
$scope.Message = "Yahoooo! we have successfully done our first part.";
});
resModule.config(function ($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl: '/Home/Index.cshtml',
controller: 'locationController'
})
.when('/Home/Index', {
templateUrl: '/Home/Index.cshtml',
controller: 'locationController'
})
.when('/Home/Registration', {
templateUrl: '/Home/Registration.cshtml',
controller: 'registerController'
})
.when('/Home/Login', {
templateUrl: '/Home/Login.cshtml',
controller: 'loginController'
})
.otherwise({ redirectTo: '/' });
});
})();
Index.cshtml
#{
// Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "Webový rezervační systém";
}
<base href="/">
<div class="container" ng-controller="locationController">
<header class="header">
<div class="headerleft">
<div class="headerlogo">
<img alt="reservation" src="../Content/pics/vetstoria-logo.jpg" width="50" height="50">
</div>
</div>
<div class="headerright">
<p class="headerlogintext">
<a class="btn headerlogin" href="/Home/Login" style="text-decoration:none">Přihlašte se</a>
</p>
</div>
</header>
<div class="content">
<h1 class="content-title">Webový rezervační systém</h1>
<p class="content-title-text">V našem rezervačním systému se můžete rezervovat na cokoliv chcete. Ať už si chcete rezervovat sportoviště, nějaký kurz nebo jiné, u nás to jde snadno.</p>
<p class="content-title-text">Pro začátek vám stačí jediné.</p>
<button class="btn-big" ng-click="setLocation('/Home/Registration')">Registrovat</button>
</div>
<!-- <ul class="menuUl">
<li>#Html.ActionLink("Register", "Registration")</li>
</ul>-->
#section Scripts{
<script src="~/Scripts/Angular_Controllers/locationController.js"></script>
}
I read some topics about this, but I don't know, if an error is in the module, or in the controller.
I had a similar issue. The template url should point to ".html" rather than ".cshtml". When you try to access files inside the Default Folders created by Visual Studio, for some reason you cannot access it. So try changing your path.

How to use ng-switch as a router for my pages with ngRoute & ngView?

Here is the highlevel skeleton of my Angular SPA. My application is about college degree offerings. In that engineering page has a separate left nav which is currently built on ng-switch which i want to convert as route. How do i do that just using angular's native routing angular-route.js?
**app.js**
(function(){
var app=angular.module("myCollege",['ngRoute']);
app.config(['$routeProvider','$locationProvider',
function($routeProvider,$locationProvider) {
$routeProvider
.when('/', {
templateUrl:"app/views/home.html",
controller:"homeController",
}
.when('/engg', {
templateUrl:"app/views/engineering.html",
controller:"engineeringController",
})
.when('/med', {
templateUrl:"app/views/medical.html",
controller:"medicalController",
})
}]);
I have left nav in engineering.html using ng-switch which i want to
convert as sub-route of the application.This left nav of engineering
page is not inside of ngView. How do i acheive this using angular's
native ngRoute/angular-route?
**engineering.html**
<div nav ng-switch on="pagename()">
<div ng-switch-when="Civil Engineering">
<div civil-directive> </div>
</div>
<div ng-switch-when="Computer Engineering">
<div computer-directive> </div>
</div>
<div ng-switch-when="Nano Engineering">
<div nano-directive> </div>
</div>
<div ng-switch-when="Electrical Engineering">
<div electrical-directive> </div>
</div>
</div>
EngineeringController.js
(function() {
var app =angular.module("collegeApp");
var engineeringController= functino($scope,$rootscope,$location)
{
$scope.pagename = function() {
return $location.path();
};
app.controller("engineeringController",['$scope','$rootScope','$location',engineeringController])
}());
The above logic is not working for me. Can someone tell me where i am doing the wrong?
Not a good practice but here's what you want to do if you want to use ng-switch:
In your html, as you write for example:
<!-- don't forget to reference your app and your controller -->
<button ng-click="goTo('/page1')">Go to page 1</button>
<button ng-click="goTo('/page2')">Go to page 2</button>
<div nav ng-switch on="pagename()">
<div ng-switch-when="'/page1'"></div>
<div ng-switch-when="'/page2'"></div>
</div>
<div ng-view> </div>
in js
Config your routes
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/page1', {
templateUrl: 'views/page1.html'
}).
when('/page2', {
templateUrl: 'views/page2.html'
}).
otherwise({
redirectTo: '/'
});
}])
and add the following in your controller:
$scope.pagename = function() { return $location.path(); };
$scope.goTo = function(page){
$location.path(page);
}
In the html above, ng-switch will use the $location.path() variable to know which view to display.
As I said this is not a good practice, because your controller isn't suppose to deal with routes.

ng-click and ng-submit doesn't work

i have a angular application with phonegap where i have a login form and login controller.
The problem is that the ng-submit doesn't work. Normaly the submit call the fonction formConnexion() but nothing happens. So, i tried with just a alert, but it's the same result...
After i tried with a ng-click and same result. Then, i wanted try to call a sample variable in the scope in the template ($scope.test) and it doesn't display. And the console.log('salut!!') doesn't dispaly when i am on the login page.
Which made me think that my controller it doesn't associate to the template.
But i have the ng-controller in my div with the good name controller.
Then, i thought that angular it's was worse installing but no because the other directives work (ng-if, ng-src, ...)
So, if you have a idea to solve this problem, I do not mind :)
here the code for the template :
login.html
<div class="row jumbotron" style="margin:10px" ng-controller="LoginCtrl">
<div class="col-lg-8 col-lg-offset-2 col-md-8 col-md-offset-2 col-sm-8 col-sm-offset-2 col-xs-8 col-xs-offset-2">
<h1>{{ test }}</h1>
<form class="form-horizontal" ng-submit="alert('alert')">
<div class="form-group">
<label for="login" class="control-label">Login</label>
<input type="text" name="login" class="form-control" ng-model="formData.login">
</div>
<div class="form-group">
<label for="password" class="control-label">Password</label>
<input type="password" name="password" class="form-control" ng-model="formData.password">
</div>
<button type="submit" class="btn btn-md btn-success">Connexion</button>
</form>
click
<img ng-src="images/accueil.png" class="accueil img-responsive">
</div>
</div>
and here the controller :
login.js
'use strict';
appStat.controller('LoginCtrl', function ($scope, $rootScope, $http, $location) {
console.log("salut!!");
$scope.formData = {};
$scope.test = "test";
$scope.toto = function() { alert('alert'); };
/**
* Connect l'user
*/
$scope.formConnexion = function () {...}
});
and here my app.js :
app.js
'use strict';
var appStat = angular.module('posStatsPhoneGap', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'ngResource',
'ui.bootstrap',
'ngMessages',
'ngAnimate',
'ngAria',
'ngTouch',
'picardy.fontawesome'
])
.config(['$routeProvider', '$compileProvider', function ($routeProvider, $compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|file|tel):/);
$compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|file|tel):/);
$routeProvider
.when('/', {
templateUrl: 'views/login.html',
controller: 'LoginCtrl'
})
.when('/main', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/stat', {
templateUrl: 'views/stat.html',
controller: 'StatCtrl'
})
.otherwise({
redirectTo: '/'
});
}
]);
Thank you in advance !
Following from my comment Try something like this:
Create a Controller file & a controller within it Create a angular
module within the controller file
Create a controller.js file then create a angular module see code below:
//Within your controller.js file
var myApp = angular.module('myApp', []);
myApp.controller('myController', function($scope, $http){
$scope.Data = "Alert Alert";
// Create a function within the scope of the module
$scope.myFunc = function(){
alert($scope.Data)
};
});
Then within your HTML file call the function on-Click see code below:
Note: Don't forget to add the controller you created into your HTML code. I usually add it in the body tag
<body ng-controller="myController">
<button ng-click="myFunc()">Make Request Button</button>
</body>
See a live example here:
http://plnkr.co/edit/sQ0z7TlyWv5fM5XyfujK?p=preview
Also a note: ng-click is mostly used for any click events you are trying to perform within your angular app but ng-submit is mostly used when working with a HTML form submission.
Use ng-submit in you form as:
<form ng-submit="submit()">
function Ctrl($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function () {
if ($scope.text) {
$scope.list.push($scope.text);
$scope.text = '';
}
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<div ng-controller="Ctrl">
<form ng-submit="submit()">Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" /> <pre>list={{list}}</pre>
</form>
<button ng-click="submit()">Submit 2</button>
</div>
</div>
I found the error. It was caused by having 2 controllers with the name 'LoginCtrl'. It was a stupid copy/paste error.
I have created one working code for the above question for 4 different type of HTML element, for complete code please follow the below URL -
http://plnkr.co/edit/Tm2Rtbt3xsv4pKzcPQCw?p=preview
<body ng-controller="ExampleController">
<button ng-click="setButton()">set button</button>
<div content="snippetContentFirst"></div>
<div content="snippetContentSecond"></div>
<div content="snippetContentThird"></div>
<div>
<ul content="snippetContentFour"></ul>
</div>
</body>

Nested views inside angular ui bootstrap modal

Here is the entrypoint of my angularjs application. What I'm trying to create is an modal with multiple views.
(function() {
'use strict';
angular
.module('app', ['ui.router', 'ui.bootstrap'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('modal', {
url: '/modal',
onEnter: ['$stateParams', '$state', '$modal', function ($stateParams, $state, $modal) {
$modal.open({
templateUrl: 'partials/modal.html',
backdrop: 'static'
});
}]
})
.state('modal.models', {
url: '/models',
templateUrl: 'partials/modal.models.html'
});
})
.run(function ($rootScope) {
$rootScope.$on("$stateChangeError", console.log.bind(console));
});
}());
and this is the main view
<!-- Modal -->
<div id="myModal">
<div class="modal-header">
<h2>Select your own car</h2>
</div>
<div class="modal-body">
<h4>Brands</h4>
<a ui-sref="modal.models">Models</a>
<div ui-view></div>
</div>
</div>
My problem is that when I click on the link ui-sref nothing happens. Why ui-router doesn't work inside a modal? I should pass in the second view that is the following named modal.models.html
<div>
<h1>Hello</h1>
</div>
For those like me that stumble along later, here's another path:
This plunker uses a simple CSS modal (rather than the fancy ui-bootstrap one) to accomplish the same end result --with the additional perk of 'sticky states' that persist underneath the modal interaction. Note that this supports substates within the modal in a uirouter-kosher way.
$stateProvider.state('modal', {
url: '/modal',
views: {
'modal': {
templateUrl: 'modal.html'
}
}
});
$stateProvider.state('modal.substate', {
url: '/substate',
template: '<h3>I\'m a substate in a modal'
});
(Credit to #christopherthielen for the example code.)
<script type="text/ng-template" id="modal.html">
<div class="modal-overlay fade">
<div class="modal-content">
<h2>Modal</h2>
This modal has a substate. <a ui-sref=".substate">Activate it</a>
<div ui-view></div>
<a ui-sref="app">Back to the app...</a>
</div>
</div>
</script>
In my own troubleshooting, the problem with the 'injected-onEnter' pattern detailed in the ui-router FAQ --which your code follows-- is that the ui-views within the injected template seem to be no longer visible/available to ui-router. Alas! Good thing there's not much required to simply roll-your-own modal window.

Categories