Laravel Framework, AngularJS - Not Routing - angularjs

I am trying to develop an application with Laravel Framework and AngularJS. However, I have the "routing" problem. I have the file "Master.blade.php". But the AngularJS "html" and "controller" files do not appear.
My Local Screen
webpack.mix.js [not problem js and sass files]
const { mix } = require('laravel-mix');
mix.scripts([
'node_modules/bootstrap/dist/bootstrap.js',
'node_modules/angular/angular.js',
'node_modules/angular-route/angular-route.js',
'node_modules/angular-cookies/angular-cookies.js',
'resources/assets/js/app.js',
'resources/assets/js/controllers/authController.js'
], 'public/assets/js/app.js')
.sass('resources/assets/sass/app.scss', 'public/assets/css/app.css');
web.php - Laravel routing
<?php
Route::get('/app', function () {
return view('layouts.master');
});
Master.blade.php
<!Doctype html>
<html ng-app="bildirioApp">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Bildirio</title>
<link rel="stylesheet" href="{{ asset('assets/css/app.css') }}">
</head>
<body>
<div class="container">
<div ng-view></div>
</div>
<script type="text/javascript" src="{{ asset('assets/js/app.js') }}"></script>
</body>
</html>
App.js
/* This is the main file where Angular is defined */
var bildirioApp = angular.module('bildirioApp', ['ngRoute', 'ngCookies']);
bildirioApp.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider.when('/login', {
templateUrl : 'resources/views/auth/login.html',
controller : 'authController',
});
$routeProvider.otherwise('/');
}
]);
authController.js
bildirioApp.controller('authController', ['$scope', function ($scope) {
}]);
login.html
<div class="row">
<div class="col-sm-4 col-sm-push-3 well">
<h1>Login</h1>
<form name="loginForm" ng-submit="doLogin(loginForm)">
<div class="form-group">
<input class="form-control" type="email" name="email" ng-model="login.username" required placeholder="Enter your email address">
</div>
<div class="form-group">
<input class="form-control" type="password" name="password" ng-model="login.password" required placeholder="Enter your password">
</div>
<input class="btn btn-success" type="submit" name="save" value="Login">
</form>
</div>
</div>

It seems like the problem you are facing is that your login.html file is not found.
When you are setting your template to
templateUrl : 'resources/views/auth/login.html'
your server is actually looking for
{app_root_folder}/public/resources/views/auth/login.html
which, of course, does not exist. That is because Angular does not have access to anything but the public folder and specific routes you define.
If you looked at the Network section of your browser's Developer Tools you will probably see a 404 error.
There are 2 ways you can fix this.
Option 1 - Create a route that serves the login.html file.
First, change your App.js routing to:
$routeProvider
.when('/login', {
templateUrl : 'login/getView',
controller : 'authController',
});
Then, add the corresponding route in web.php which will serve the login.html file:
Route::get('/app', function () {
return view('layouts.master');
});
Route::get('/login/getView', function () {
return view('auth.login');
});
This, hopefully solves your problem. If not - monitor the Network requests in the Developer Tools to see if the login.html is found or not. Also make sure all other files are actually loaded correctly (i.e App.js).
Option 2 - Move your login.html to the public folder (not recommended)
You can move the login.html into the public folder (public/resources/views/auth/login.html).
This is NOT my preferred way of doing it since it breaks your MVC pattern.
I usually like to have all my view files in the resources/views folder and not split them between resources/views and public.
Also, when they are in the resources/views folder you can use .blade files so serve to Angular. This way you can do server-side rendering before it reaches Angular (i.e login.blade.php).
Hope this helps!

Related

Why does this code break once "app" and the ng-controller are added?

This code is virtually verbatim from egghead.io, but it is not working at all unless I remove ="app" and remove the ng-controller attribute from the <body> element. (And of course the last <script> element gets ignored in the process—the code that would normally be in app.js.) Of course removing those bits prevents anything else from working or being added.
<!doctype html>
<html ng-app="app">
<head>
<script src="http://code.angularjs.org/angular-1.0.0.min.js"></script>
<script src="http://code.angularjs.org/angular-ui-router-1.0.0.min.js"></script>
<script>
angular.module('app', ['ui.router'])
.controller("FirstCtrl", function FirstCtrl() {
var first = this;
first.greeting = "First";
});
</script>
</head>
<body ng-controller="FirstCtrl as first">
<div>
<input type="text" ng-model="first.greeting" placeholder="First Name">
<hr>
<h1>{{ first.greeting }} World!</h1>
</div>
</body>
</html>
Here's similar code on JSFiddle. (It's only similar because JSFiddle imposes constraints that make it impossible to post identical code. It has the same problem, so I assume the differences are insignificant for tracking down the source of the bug.)
Where is the bug? Why is this not working?
With latest angular dependency it worked for me.
<!doctype html>
<html ng-app="app">
<head>
<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-ui-router/0.2.15/angular-ui-router.min.js"></script>
<script>
angular.module('app', ['ui.router'])
.controller("FirstCtrl", function FirstCtrl() {
var first = this;
first.greeting = "First";
});
</script>
</head>
<body ng-controller="FirstCtrl as first">
<div>
<input type="text" ng-model="first.greeting" placeholder="First Name">
<hr>
<h1>{{ first.greeting }} World!</h1>
</div>
</body>
</html>
You are using angular ui-router but not using it the way you are supposed to be. Check the documentation here to get a clearer idea. Angular UI router loads its contents in a container containing ui-view attribute. As per documentation
AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine. Unlike the $route service in Angular core, which is organized around URL routes, UI-Router is organized around states, which may optionally have routes, as well as other behavior, attached.
You need to load different states in your ui-view and also pass values in different states in the process. You need to add dependencies for $stateProvider and $urlRouterProvider in your app config for a completely functional angular ui router implementation. This being told what you need to do is like below -
And also check out the working example in PLUNKER
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<title>AngularJS: UI-Router Quick Start</title>
<!-- Bootstrap CSS -->
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container">
<div class="row">
<div class="span12">
<div class="well" ui-view></div>
</div>
</div>
<!-- Angular -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.js"></script>
<!-- UI-Router -->
<script src="//angular-ui.github.io/ui-router/release/angular-ui-router.js"></script>
<!-- App Script -->
<script>
var myapp = angular.module('myapp', ["ui.router"])
myapp.config(function($stateProvider, $urlRouterProvider){
// For any unmatched url, send to /route1
$urlRouterProvider.otherwise("/route1")
$stateProvider
.state('route1', {
url: "/route1",
templateUrl: "route1.html",
controller: function($scope) {
$scope.greeting = "First";
}
})
})
</script>
</body>
</html>

Change AngularJS urls with ng-model

Is there any way to change AngularJS urls with ng-model?
var scotchApp = angular.module('scotchApp', ['ngRoute']);
scotchApp.controller('mainController', function($scope) {
$scope.gettext = function (){
};
});
<!-- index.html -->
<!DOCTYPE html>
<html ng-app="scotchApp">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
<script src="eventChange.js"></script>
</head>
<body ng-controller="mainController">
<div class="container">
<div class="row">
<div class="col-sm-1">Search</div>
<div class="col-sm-3"><input type="text" class="form-control" ng-model="search" ng-change="gettext()"></div>
</div>
</div>
</body>
</html>
I need to change the URL into something like this http://localhost/angulRoute/search=myVal when user type 'myVal' in the search box (actually inside gettext() function with search value)
You can do something like this in your controller:
$scope.query = $location.search().q;
$scope.$watch('query', function(newValue) {
$location.search('q', newValue);
});
You'd need to inject $location into your controller, and make sure in your route config includes:
reloadOnSearch: true
That would result in a URL like http://localhost/myRoute?q=myVal
Note: I would also add ng-model-options="{updateOn:'blur'}" to your input, to prevent updating the URL on every key press.
EXAMPLE
Here is a working example of how to do this: http://plnkr.co/edit/tphqPeJ0dO74Ux7WpXlU?p=preview
Note that, because of the way plnkr.co works, you won't see the URL changes in the address bar on that site. If you download the code and run it locally, the URL would be updated in the address bar.
Hi I found a javascript solution for that.
$scope.gettext = function (search){
window.history.pushState("object or string", "Title", "/angulRoute/search="+search);
};
with <input type="text" class="form-control" ng-model="search" ng-change="gettext(search)" > worked for me. However anyone have an AngulerJs solution they are welcome :D

templateUrl for AngularJS (routing)/MVC application never loads templates

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.

Firefox addon using AngularJS - "ng-src" not working

I am working on a Firefox add-on that uses AngularJS.
The issue is with 'ng-src'. It does not load the referenced image.
When I switch to 'src' the image loads fine.
Example.html and 'icon-32.png' are within same folder.
Appreciate your help in making sense of this issue.
Below are the code snippets.
Example.html
<html ng-app="MyAddon" ng-csp>
<head>
</head>
<body ng-controller="MainCtrl" dir="{{dirr}}">
<div border="0">
<img ng-src="{{logo}}" width="32" align="center">
<input id="textbox" type="text"> </input>
<button id="textboxbutton" type="button"> {{ButtonText}}</button>
</div>
<script src="lib/angular.min.js"></script>
<script src="scripts/app.js"></script>
</body>
</html>
app.js:
function MainController($scope) {
$scope.ButtonText= 'Hit me!';
$scope.dirr = 'rtl';
$scope.logo= 'icon-32.png';
};
var MyModule = angular.module('MyAddon', [])
.controller('MainCtrl', MainController)
It is because angular keeps adding unsafe: to your image url. I think this is the solution, please try: Angular changes urls to "unsafe:" in extension page
and whitelist the resource:// urls. without unsafe: it works.
I saw this from using DOM Inspector:

AngularJS, UI Bootsrap, MVC Frontend - index.html not loading login.html in ng-view

I am working on MVC project using Maven.
Backend: Spring Boot framework (Tomcat server), MySQL db, hibernate for db binding, dao extends CrudeRepository, NO SERVICE (no need, small app), 4 classes (model) and 4 controllers.
So far, there was no problem here. But, when I started working on frontend, I have experienced one or more problems.
Frontend: In my index.html page I have included AngularJS and (Angular) UI Bootsrap via cdn, app.js and userController.js (my files, userControll is not important for my problem I suppose but I have to point out it's presence in the index.html), data-ng-app="collectionsApp" (collectionApp is app that is created via app.js) and data-ng-view (this file should load another html file named login.html in folder view).
In file app.js (/webapp/scripts/app.js) I have created collectionsApp application and function($routeProvider).
When I do "Run As Java Application" on Application.java (class in backend where main function is located wit SpringApplication.run(Application.class, args) program runs, server is started and hibernate makes connection to database with no errors or warnings.
When I open the Chrome and type localhost:8095 (I have changed port from usual 8080 to 8095 on purpose via application.properties file because on my machine 8080 was blocked and I suppose that this is not a problem) in the adress bar I can see only blank page.
This is the problem because data-ng-view should load login.html bout i does not!
My index.html file:
<!DOCTYPE html>
<html data-ng-app="collectionsApp">
<head>
<meta charset="UTF-8">
<title>Collections</title>
<link
href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body>
<div data-ng-view></div>
</body>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.10.0/ui-bootstrap-tpls.js"></script>
<script src="/scripts/app.js"></script>
<script src="/scripts/controller/indexController.js"></script>
</html>
My login.html file:
<div class="container">
<form class="form-signin" role="form">
<h1 class="form-signin-heading">Please sign in</h1>
<input type="email" class="form-control" placeholder="Email address"
required autofocus> <input type="password"
class="form-control" placeholder="Password" required>
<div class="checkbox">
<label> <input type="checkbox" value="remember-me">
Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign
in</button>
</form>
</div>
My app.js file:
var collectionsApp = angular.module('collectionsApp', [ 'ngRoute' ]);
collectionsApp.config(function($routeProvider) {
$routeProvider.when('/login', {
templateUrl : '/view/login.html',
controller : 'loginController'
}).
otherwise({
redirectTo : '/login'
});
});
My folder structure .
You have to include //cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-route.min.js
to be able to inject the $routeProvider and use routing.
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular-route.min.js"></script>

Resources