I'm trying to split my angularjs controllers into files but failing everytime.
Directory Structure:
--public--
--js/controller/resturant.js
--js/master.js
--index.php
Code for master.js
angular.module("rsw",['rsw.controller']);
Code for resturant.js
angular.module('rsw.controller').controller('resturant', ['$scope', '$http', function($scope, $http){
$scope.data="Test"
}]);
Code for index.php
--
<div ng-app="rsw">
<span ng-controller="resturant">
{{ data }}
</span>
</div>
--
EDIT:
I've included only 'master.js' in my index.php, do I need to import 'resturant.js" too?
You need to use the correct module definition call. That is, angular.module(name) retrieves a module and angular.module(name, [requires]) creates one.
angular.module('rsw.controller', [])
.controller('resturant', ['$scope', '$http', function($scope, $http){
$scope.data="Test"
}]);
After creating your module, you need to then make it a dependency of your app:
angular.module("rsw",['rsw.controller']);
Fixed code:
angular.module("rsw", ['rsw.controller']);
angular.module('rsw.controller', [])
.controller('resturant', ['$scope', '$http',
function($scope, $http) {
$scope.data = "Test"
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="rsw">
<span ng-controller="resturant">
{{ data }}
</span>
</div>
I think you had set up your controller wrong.
Try typing this instead:
angular.module('rsw').controller('resturant', ['$scope', '$http', function($scope, $http){
$scope.data="Test"
}]);
something like this should work...
file structure:
--public
--js
--controllers
--resturant.js
--app.js
--appRoutes.js
--views
--index.php
// resturant.js
angular.module('rswCtrl', []).controller('RswController', [$scope, function($scope) {
}]);
// appRoutes.js
angular.module('appRoutes', []).config(['$routeProvider','$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/index.php',
controller: 'RswController'
});
}]);
// app.js
angular.module('myApp', ['appRoutes', 'rswCtrl']);
and then don't forget to include paths to all these files in your index.php file. Hope I'm not missing something..
Related
I've been struggling with getting my AngularJS app to display a view based on a template.
The issue: ui-router seems to be correctly "routing" all the files, because the template file (landing.html) is being delivered to the console as an object (see console.log(result) in main.js below). Nevertheless, the template file is not being displayed in the app where <div ui-view></div> is supposed to be.
index.html:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
##include('partials/head.html')
<body>
##include('partials/header.html')
<div ui-view></div>
##include('partials/footer.html')
</body>
</html>
main.js:
angular.module('myApp', [
'ui.router'
])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('landing', {
url: '/',
controller: 'LandingCtrl as landing',
templateUrl: 'templates/landing.html'
});
$urlRouterProvider.otherwise('/landing');
}])
.run(['$http', '$templateCache', function($http, $templateCache) {
$http.get('templates/landing.html', {
cache: $templateCache
}).then(function(result) {
console.log(result);
});
}]);
My template file landing.html:
<main class="content">
##include('partials/search.html')
<h2>Show me the contents of landing.html!</h2>
</main>
I'm using grunt and made sure to have it both watch and copy the /templates into /dist. Overall the Angular app is behaving correctly (no ng errors in the console).
Also, if instead of specifying a template file (templateURL), I simply use template: <h2>Show me the contents of landing.html!</h2> in main.js then this is rendered in the view. There's something preventing a file from being rendered.
Question: Given ui-router is correctly finding and routing all files, does anyone have an idea as to why the app is simply not displaying the template file?
Edit Here is LandingCtrl.js:
(function() {
function LandingCtrl($scope, $location, $anchorScroll) {
$scope.goTo = function(id) {
$location.hash(id);
console.log($location.hash());
$anchorScroll();
};
}
angular
.module('myApp')
.controller('LandingCtrl', ['$scope', '$location', '$anchorScroll', LandingCtrl]);
})();
in your main.js file change the url of Landing State as below:
angular.module('myApp', [
'ui.router'
])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('landing', {
url: '/landing',
controller: 'LandingCtrl as landing',
templateUrl: 'templates/landing.html'
});
$urlRouterProvider.otherwise('/landing');
}])
.run(['$http', '$templateCache', function($http, $templateCache) {
$http.get('templates/landing.html', {
cache: $templateCache
}).then(function(result) {
console.log(result);
});
}]);
I am trying to have a link in my page such as:
<a ng-href="#/Page/{{x.ID}}">{{x.ID}}</a>
Which succesfully gets to the angular controller but however the $routeparams are null when I am expecting to get the {{ x.ID }} back:
pageController.js
angular.module("myApp.Pages").controller("pageController", ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
console.log($routeParams);
}]);
And am referencing the state in my $stateprovider such as (in appRouting.js):
$stateprovider.state('Page', {
url: '/Page/:userId',
templateUrl: 'App/Pages/page.html',
controller: 'pageController'
})
my app.js
angular.module("myApp", [
// User defined modules
'myApp.Pages', // Pages
'myApp.Core', // Core
// Angular modules
'ui.router', // state routing
'ngRoute', // angular routing
'LocalStorageModule', //local browser storage
'angularRangeSlider',
'ngFileUpload'
])
Any ideas?
$stateParams instead of $routeParams
I am building my first angularJS app and I am struggling with getting parameters from my URL into my code.
The URL has a single parameter, subject and all I am trying to do at this stage is display it on the screen...
Javascript:
app.config(function($routeProvider) {
$routeProvider
.when('/setspage/:subject',
{templateUrl: "setspage.html",
controller: "setsController"
}),
});
angular.module("app").controller("setsController", function($scope, $routeParams, $http) {
$scope.selectedSubject = routeParams.subject
});
HTML:
<body ng-controller="setsController">
<div class="page-header">
<h1>Subject : {{selectedSubject}}</h1>
</div>
<script src="./node_modules/angular/angular.js"></script>
<script src="./node_modules/angular-route/angular-route.js"></script>
<script src="scripts/app.js"></script>
</body>
change
routeParams.subject
to
$routeParams.subject
Change your controller like this
angular.module("app").controller("setsController",['$scope', '$routeParams', '$http', function($scope, $routeParams, $http) {
$scope.selectedSubject = $routeParams.subject
}]);
I had an angular setup that looked like this:
var dashboard = angular.module('Dashboard', ["ngRoute", "highcharts-ng"]);
dashboard.config(function($routeProvider, $locationProvider){
$routeProvider.when('/route1', {
templateUrl: 'route1.html',
controller: 'DefaultCtrl'
});
})
.controller('DefaultCtrl', function($scope, $rootScope, $http, settings){
function($scope, $rootScope, $http, settings){
$http.get("http://admin.gmserver.net/games/all?userId=" + settings.userId).success(function(data){
$scope.games = data;
$rootScope.gameId = "";
$rootScope.gameName = "";
$rootScope.apiName = "";
$rootScope.$broadcast("loaded");
});
}
})
And this worked. I then tried to split them up into multiple files (one for each controller), and now it looks like this:
module file:
angular.module('Dashboard', ["ngRoute", "highcharts-ng"]);
angular.module('Dashboard').config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider){
$routeProvider.when('/route1', {
templateUrl: 'route1.html',
controller: 'DefaultCtrl'
});
}
])
controller file:
angular.module('Dashboard').controller("DefaultCtrl", ['$scope', '$rootScope', '$http', 'settings',
function($scope, $rootScope, $http, settings){
$http.get("http://admin.gmserver.net/games/all?userId=" + settings.userId).success(function(data){
$scope.games = data;
$rootScope.gameId = "";
$rootScope.gameName = "";
$rootScope.apiName = "";
$rootScope.$broadcast("loaded");
});
}
]);
Now when I load the page I get this:
I am loading the files like this:
<script src="http://code.highcharts.com/adapters/standalone-framework.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="/media/js/highcharts-ng.min.js"></script>
<!-- Begin app code -->
<script src="/admin/Dashboard.js"></script>
<!-- Built with smarty -->
<script>
angular.module('Dashboard').value("settings", {
userId: "{$userId}",
secret: "{$secret}"
});
</script>
<script src="/admin/components/default/DefaultController.js"></script>
<script src="/admin/components/game/GameController.js"></script>
<script src="/admin/components/leaderboard/LeaderboardController.js"></script>
<script src="/admin/components/newsFeed/NewsFeedController.js"></script>
I do notice that commenting out one of the following stops the Aw, Snap error.
DefaultController.js file
Inline JavaScript
highcharts-ng.min.js file
Edit:
I changed the name of the module to my site's name and made the Dashboard a dependency like this:
angular.module('GMServer', ["ngRoute", "highcharts-ng", "Dashboard"]);
angular.module('Dashboard')
This fixes the "Aw, Snap" issue, but now I get this error: https://docs.angularjs.org/error/$injector/nomod?p0=Dashboard
I'm not entirely sure what happens when you call the same angular.module several times but I would avoid it.
You want to save the module globally so then you can reference it in different files instead of calling angular.module('Dashboard') each time:
window.Dashboard = angular.module('Dashboard', ["ngRoute", "highcharts-ng"]);
window.Dashboard.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider){
$routeProvider.when('/route1', {
templateUrl: 'route1.html',
controller: 'DefaultCtrl'
});
}
])
and
window.Dashboard.controller("DefaultCtrl", ['$scope', '$rootScope', '$http', 'settings',
function($scope, $rootScope, $http, settings){
$http.get("http://admin.gmserver.net/games/all?userId=" + settings.userId).success(function(data){
$scope.games = data;
$rootScope.gameId = "";
$rootScope.gameName = "";
$rootScope.apiName = "";
$rootScope.$broadcast("loaded");
});
}
]);
You'll just need to make sure your <script> tags are included in the correct order.
Avoid polluting the window object though, you may wanna namespace everything under window.App or use someting like requireJS or Browserify.
Edit
It's perfectly safe to retrieve a module like the OP is doing as pointed out #Sunil and documented here
I am having some issues trying to use the Angular dependency injection with different modules. At the moment, I have the following. In my index.html, the files are loaded in the following order (end of <body> tag):
network.js
authentication.js
login.js
app.js
network.js
angular.module('services.network', [])
.factory('Network', ['$http', '$state', function ($http, $state) { ... }]);
authentication.js
angular.module('services.authentication', ['services.network'])
.factory('Authentication', ['$state', 'Network', function ($state, Network) { ... }]);
login.js
angular.module('controllers.login', [])
.controller('LoginCtrl', ['$scope', function ($scope) { ... }]);
app.js
var app = angular.module('parkmobi', [
'ngRoute',
'services.network',
'services.authentication',
'controllers.login'
]);
app.run(['$rootScope', function ($rootScope) {
$rootScope.$on('$viewContentLoaded', function () {
$(document).foundation('reflow');
});
}])
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
});
}]);
Up until this point, everything seems to be quite happy. Now, however, I want to use the Authentication service in the LoginCtrl, which I would have thought is done as follows:
login.js
angular.module('controllers.login', ['services.authentication'])
.controller('LoginCtrl', ['$scope', 'Authentication', function ($scope, Authentication) { ... }]);
However, this causes the following injection error:
Error: [$injector:unpr] http://errors.angularjs.org/1.3.15/$injector/unpr?p0=%24stateProvider%20%3C-%20%24state%20%3C-%20Authentication
R/<#http://localhost/testapp/vendor/angularjs/angular.min.js:6:417
Error came because you've injected $state provider in your Authentication factory, without having ui.router module in app.js parkmobi module.
It should use $route instead of $state as your are doing your route in angular-router.
angular.module('services.authentication', ['services.network'])
.factory('Authentication', ['$route', 'Network', function ($route, Network) { ... }]);
Or if you want to use ui-router then you need to use $stateProvider while registering states & ui.router module should be include in your app.