Angular + Laravel : loading view via ngRoute - javascript

I'm facing this problem when combining Laravel and Angular:
Following a very simple tutorial I found online, I was trying to load a view using the ng-view directive. However, I am unable to actually load the template. This is my app.js code:
(function() {
var app = angular.module('profuApp', ['ngRoute']);
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when('/inicio', {
templateUrl: '../templates/inicio.html',
controller: 'homeCtrl'
})
.otherwise({ redirectTo: '/' });
}]);
app.controller('homeCtrl', ['$scope', '$http', function($scope, $http) {
$http.get('http://localhost:8888/profucom/public/getData').success(function(data) {
$scope.datos = data;
});
}])
})();
My file tree:
app/
bootsrap/
public/
js/
angular.min.js
angular-route.min.js
app.js
templates/
inicio.html
. . .
The site loads normally, but when I watch the source code, instead of watching the template inside of inicio.html, this happens...
Code with within my index.blade.php file
<div ng-view></div>
Code I see in the browswer's source code
<!-- ng-view: -->
The network tab on Chrome does not show a 404 error trying to load the view.
What I've tried so far:
Placing templates inside the js folder (templateUrl: 'templates/inicio.html')
Placing templates inside the public folder (templateUrl: '../templates/inicio.html')
also, templateUrl: '/public/templates/inicio.html'
Placing templates inside the root folder (templateUrl: '/templates/inicio.html')
Placing just the file inside the js folder: (templateUrl: 'inicio.html')
None of the above seem to work. Any help, please?
EDIT I also see this happenning in the url: instead of myapp/public/inicio it loads like myapp/public/inicio#/

Where is your index.blade.php located? templateUrl should be the path to the template from whatever file loads the app.js code (I'm assuming that's index.blade.php). So if that's in the root directory, templateUrl: '/public/templates/inicio.html'
As for the issue with the #, read this somewhat related question

Once again, it was nothing but a human mistake. I'm sorry and thankful at the same time for those who spent time trying to answer and comprehend my problem. This is the solution:
I was using the latest stable version directly from a CDN, version 1.3.5; however - and just to see what'd happen - I changed to version 1.2.28. What's the difference? A little syntax.
Instead of what I did above...
app.controller('homeCtrl', ['$scope', '$http', function($scope, $http) {
. . .
I did this:
app.controller('homeCtrl', function($scope, $http) {
. . .
Changing from one version to another was the answer, and changing a little the syntax.
I hope this helps anyone as distracted as I was.

Related

module dependency with ngRoute breaks angular rendering

I am trying to use Mean stack in my website project. I am using ngRoute for routing and I want to add bootstrap carousel to my main page. I am trying to put angular team carousel component from this page.
While I am trying to implement this, I realize as soon as I try to add module dependency ( which is var app = angular.module('myApp', []) ) to my controller , angular breaks (without any error) and nothing appear in page. If I delete, everything is working normal. I assume this is related with routing ?
Project Structure;
-myApp
-node_modules
package.json
server.js
-public
-controllers
-lib
-views
app.js
index.html
app.js ;
(function(){
var app = angular.module('filmSevmem', ['ngRoute']);
app.config(function($routeProvider){
$routeProvider
.when('/main', {
templateUrl: 'views/main.html',
controller: 'MainController'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutController'
})
.when('/contact', {
templateUrl: 'views/contact.html',
controller: 'ContactController'
})
.otherwise({redirectTo:'/main'});
});
})();
MainController.js;
(function(){
var app = angular.module('myApp');
var MainController = function ($scope, $http) {
....... // codes from carousel
.......
app.controller('MainController', MainController);
})();
If I add , [] or ['ngAnimate', 'ui.bootstrap'] or anything to right of 'myApp', nothing work and I get empty page from my localhost. What can cause this problem ? What should I do ? Thank you.
var app = angular.module('myApp'); means get me the module myApp.var app = angular.module('myApp', [listOfDependencies]); means create the module myApp with all of the listed dependencies. So if you put square brackets in app.js AND in mainController.js, then you overwrite the previously created. The simplest solution would be to add ngAnimate and ui.bootstrap in your app.js like this: var app = angular.module('myApp', ['ngRoute','ngAnimate','ui.bootstrap']);
If you don't want to have all your dependencies in your root module, you can make submodules like var controllers = angular.module('myApp.controllers', ['ngAnimate']), and include this in your app.js like var app = angular.module('myApp', ['myApp.controllers']);
Why you are creating two different modules? And even you are not injecting the first module while creating the second.
By no chance your application is gonna work until and unless you code everything using single module or inject one module in another!

How can I have multiple controller files?

SOLVED
So after viewing your responses and making minor changes to my code, I found a simple typo which prevented me to reach the result I was after. So thank you all to helping with where I was going wrong, I've now got the controllers seperated and everything's working as planned!
----
I am currently developing a hybrid mobile application using Cordova, Ionic and AngularJS within Visual Studio 2015. Due to the vast amount of code I have in my single controller.js file, I want to separate the code so I have a .js controller file per template; instead of everything in one file. Unfortunately, I I do not understand how to pull this off (learning AngularJS still). I've done some researched but the majority of examples I have seen show a very simple demo, which I replicate with my own code but it still doesn't work. So I was hoping if someone can give me an insight where I may be going wrong.
File Structure in /www
index.html
/js
app.js
controllers.js
/js/controllers
login.js
sales.js
/templates
login.html
sales.html
/js/app .js
angular.module('main', ['ionic', 'main.controllers', 'chart.js', 'ngCordova', 'ngIOS9UIWebViewPatch', 'angular.filter'])
.config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$stateProvider
.state('login', {
cache: false,
url: "/login",
templateUrl: "templates/login.html",
controller: "LoginCtrl"
})
.state('sales', {
cache: false,
url: "/sales",
templateUrl: "templates/sales.html",
controller: "SalesCtrl"
})
$urlRouterProvider.otherwise('/login')
$ionicConfigProvider.views.swipeBackEnabled(false);
});
/js/controllers.js
angular.module('main.controllers', ['ionic', 'ngCordova']);
/js/controllers/login.js
angular.module('main.controllers', [])
.controller("LoginCtrl", function ($scope, $state, $cordovaSQLite, $timeout, $ionicPopup, $cordovaDevice, $ionicLoading, $cordovaKeyboard, $cordovaToast) {
$ionicLoading.show({
template: 'Loading...'
});
// DO STUFF
/js/controllers/sales/js
angular.module('main.controllers', [])
.controller("SalesCtrl", function ($scope, $state, $http, $ionicLoading, $cordovaSQLite, $cordovaToast) {
$ionicLoading.show({
template: 'Loading data...'
});
// DO STUFF
Following this structure, I get this error (quote below): https://docs.angularjs.org/error/ng/areq?p0=LoginCtrl&p1=not%20a%20function,%20got%20undefined
Argument 'LoginCtrl' is not a function, got undefined
I managed to get it to work slightly, only when I had login.js and not sales.js, but of course $state.* stopped working when trying to change template. So I know that wasn't 100% either. Hopefully this will make sense, fi it doesn't just clarify what I may be not making sense in, and I shall explain more if need be, appreciate any help. :)
EDIT
index.html
<!-- App references -->
<link href="css/ionic.css" rel="stylesheet" />
<link href="css/angular-chart.css" rel="stylesheet" />
<link href="css/index.css" rel="stylesheet" />
<script src="lib/ionic/ionic.bundle.js"></script>
<script src="lib/ngCordova/ng-cordova.js"></script> <!-- Must be after Ionic but before Cordova-->
<script src="cordova.js"></script>
<script src="scripts/index.js"></script>
<script src="lib/angular-cookies/angular-cookies.min.js"></script>
<script src="lib/angular-chart/Chart.min.js"></script>
<script src="lib/angular-chart/angular-chart.min.js"></script>
<script src="lib/angular-ios9-uiwebview.patch.js"></script>
<script src="lib/angular-filter/angular-filter.min.js"></script>
<script src="js/directives/favourite.js"></script>
<script src="js/controllers.js"></script>
<script src="js/controllers/login.js"></script>
<script src="js/controllers/sales.js"></script>
<script src="js/app.js"></script>
You are redefining your module again & again in your each controller file. Which is clearing out old registered controller from that module.
You have already defined that module in your /js/controllers.js.
angular.module('main.controllers', ['ionic', 'ngCordova']);
So reuse that module in other Javascript files when your are binding any component to it as below.
angular.module('main.controllers')
The best approach is that you clearly separate module creation from module usage.
modules.js:
angular.module('main', ['main.sales']);
angular.module('main.sales', []);
src/sales/scripts/sales-controller.js:
angular.module('main.sales').controller(function() {});
If you concat and minify your js files via grunt or gulp, you should always explicitly include modules.js first, afterwards you can include the rest via a pattern like 'src/**/*.js' for example.
This way the modules are always defined before they are used. If that's not the case, angular will complain about a non existing module.
PS: it's way better to create functional modules (sales related functionality in 1 module) instead of technical modules (all controllers in 1 module)
You are declaring the main.controllers module twice, once for each controller. Also, it's not strictly required to declare a separate module for the controllers, you could just declare the controllers within your main module. Some would argue that you lose reusability - and they would be right - but depending on the size of your project and how tightly coupled your controllers are with your application (90% of the time the answer is: very) you could go that way. Since you are probably just starting out, try doing something like this:
js/app.js
angular.module('main', ['ionic', 'chart.js', 'ngCordova', 'ngIOS9UIWebViewPatch', 'angular.filter'])
.config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$stateProvider
.state('login', {
cache: false,
url: "/login",
templateUrl: "templates/login.html",
controller: "LoginCtrl"
})
.state('sales', {
cache: false,
url: "/sales",
templateUrl: "templates/sales.html",
controller: "SalesCtrl"
})
$urlRouterProvider.otherwise('/login')
$ionicConfigProvider.views.swipeBackEnabled(false);
});
Note that I am no longer depending on main.controllers? That's because next I'm doing this:
angular.module('main')
.controller("LoginCtrl", function ($scope, $state, $cordovaSQLite, $timeout, $ionicPopup, $cordovaDevice, $ionicLoading, $cordovaKeyboard, $cordovaToast) {
$ionicLoading.show({
template: 'Loading...'
});
// DO STUFF
And this:
angular.module('main')
.controller("SalesCtrl", function ($scope, $state, $http, $ionicLoading, $cordovaSQLite, $cordovaToast) {
$ionicLoading.show({
template: 'Loading data...'
});
// DO STUFF
The different controllers can (and should) be declared each in a separate file, so that you have a clear structure. It might be more correct to have a separate module for the controllers, and I fear my opinion might be unpopular, but I don't really see the point - whereas I strongly urge you to separate your services and your directives into different modules, since it's much more likely that you're going to use them again in other projects.
My suggest we will organize code by split to the module, and inject it in the app.js file
This is detail my way: https://mymai91.github.io/ionic/2016/07/01/ionic-structure-code-for-project.html
Code demo: https://github.com/mymai91/mymaiApp
to anyone looking at the "solved code"...
The Square brackets in the inner controlleres should be removed:
angular.module('main.controllers', [])
-->
angular.module('main.controllers')

$routeParams not populating

Some I'm new to routing and single page web apps, but I've been trying to learn Angular correctly. There's some trouble I'm experiencing with it however and a few weird questions. I followed a guide on structuring your directory and mine looks something like this:
app/
components/
profile/
profile.html
ProfileModel.js
ProfileController.js
ProfileFactory.js
app.module.js
app.routes.js
My main module is located in app.module.js and is dependency injected with ngRoute and profile.app (the module for profile view from ProfileModel.js). It is declared like this:
angular
.module('app', ['ngRoute', 'profile.app'])
.controller('MainController', MainController);
function MainController() {
this.message = 'This is the home page';
}
Then in my app.routes.js file, I have declared all the routes the applications needs (so far only one, which is profile):
angular
.module('app')
.config(routeConfig);
routeConfig.$inject = ['$locationProvider', '$routeProvider'];
function routeConfig ($locationProvider, $routeProvider) {
$routeProvider
.when('/user/:user_id', {
templateUrl: '/app/components/profile/profile.html',
controller: 'ProfileController',
controllerAs: 'profile'
}
)
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
}
This is my ProfileController.js:
angular
.module('app.profile')
.controller('ProfileController', ProfileController);
ProfileController.$inject = ['ProfileFactory', '$routeParams'];
function ProfileController(ProfileFactory, $routeParams) {
var vm = this;
vm.user_id = $routeParams.user;
console.log($routeParams.user_id);
vm = ProfileFactory.userProfile(vm.user_id); //Gets the profile of the user and sets to to vm
}
So I have two main questions. $routeParams.user_id is logged as nothing despite I have defined the route in app.routes.js. This is weird because I have an ng-view directive in my index.html (the HTML file that includes every single .js file). Which means that I should have immediate access to the routing parameters once the controller and its dependencies are instantiated. However, when I go to http://example.com/user/1, I get nothing logged (undefined).
My second question is I included ngRoute as a dependency in profile.app and my main module (in which profile.app is a dependency). However, I later removed ngRoute from profile.app as a dependency, yet I left the injection of $routeParams inside my ProfileController and AngularJS didn't complain at all. This seems weird because the dependency is no longer explicitly present inside profile.app. So how come I can still seemingly inject $routeParams despite not having ngRoute in my profile.app module? Is it because it is getting ngRoute from the main module?
I believe the problem is that you are setting controllerAs to 'profile' but then in the controller you write var vm = this;
These two need to be the same so you could write controllerAs: 'vm', or var profile = this;

Routing error in AngularJS

What's wrong with this AngularJS configuration code?
(function () {
var ip = 'x.x.x.x';
var app = angular.module('cmal', ['controllers', 'directives', 'services', 'ngRoute'])
.constant("baseUrl", "http://" + ip + ":303/angular")
.config( function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/', { templateUrl: "index.html"});
$routeProvider.when('/users', { templateUrl: "users.html"});
$routeProvider.otherwise({template: "Sorry, the page you are trying to reach doesn't exist."});
});
})();
EDIT: it's not the slash error. This still doesn't work for me and all i get in the console is "Uncaught object"
EDIT 2: Well i didn't realize you needed to import another js script for routing. But so now that I have done that, I get no error, but none of the routes work.
You are probably not including the separate angular-route script.
Take a look at this answer for more details.
This isn't really an answer, but an alternative solution...I used a separate routing framework.
UI-Router (a link to the egghead tutorial)

AngularJS locationProvider Routing

I'm very new to Angular and I'm currently building a few test/dummy apps to get my head around the way it works and become more-familiar with SPA's in Angular. However, I've stumbled into an issue when I start adding routes to my application and loading the content via ng-view
$locationProvider doesn't seem to be working correctly because if I go to localhost/sdfsdf then I get cannot GET /sdfsdf when in reality the page should be redirecting to /cocktails.
routes.js
var cocktailApp = angular.module('cocktailApp', ['ngRoute', 'cocktailControllers']);
cocktailApp.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider
.when('/cocktails', {
templateUrl: '/partials/cocktail-list.html',
controller: 'cocktailsController'
})
.otherwise({
redirectTo: '/cocktails'
});
$locationProvider.html5mode(true);
}]);
Angular only recognizes anchor URL syntax for URLs pasted directly on the browser. So you have to you try http://localhost/#/sdfsdf instead to make your routing work. Please note that anchor syntax /# was added in previous URL.

Categories

Resources