using directives breaks ng-view in angular, how to? - javascript

i have a index.html:
<body ng-app="app">
<topmenu></topmenu>
<div ng-view=""></div>
then inside a views folder i have main.html and topmenu.html
there is a route:
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
and a directive
var App = angular.module('app', []);
App.directive('topmenu', function () {
return {
replace: true,
restrict: 'E',
templateUrl: 'views/topmenu.html'
};
});
the problem is when i include the directive.js file and place the <topmenu></topmenu> tag the main.html doesn't load no more
any ideas?

In your directive file you don't need to initialize a variable with your module and dependencies a second time. So this:
var App = angular.module('app', []);
should be removed from that file.

in directive.js
remove this, it will create a new angular module with name 'app'
var App = angular.module('app', []);
if you want get module from angular you can do
var App2 = angular.module('app');
console.log(App === App2) // true
and make sure you already created your 'app' module before you load directive.js,
for example, if you have 2 JS file
<script src="index.js"/>
<script src="directive.js"/>
in index.js do
var App = angular.module('app', []);

Related

How to use one module for multiple controllers

How to use one module for multiple controllers, when these controllers are in different js files.
I have 3 js file
1. app.js
2. Login. js
3. Register.js
app.js
var app = angular.module("myApp", ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'Login/login.html',
controller: 'myCtrl'
})
.when('/register', {
templateUrl: 'Register/register.html',
controller: 'registerCntrl'
})
})
Login.js
var app = angular.module("myApp");
app.controller("myCtrl", function ($scope) {
$scope.login = function (data) {
console.log(data);
if (data.name == 'pinku' && data.pswd == '1234') {
console.log("Login Successfull");
} else {
console.log("Not successful");
}
};
$scope.moreInfo = function () {
alert("M in more info");
}
});
Register.js
var app = angular.module("myApp");
app.controller("registerCntrl", function ($scope) {
});
I have defined mymodule in my app.js file now i want to register my controller to that module and controllers are in different class. I have injected ng-Route in app.js. In login m using already defined module but m getting error
'Failed to instantiate module ngRoute due to:'
Thanks in advance
You can rather do:
angular.module("myApp")
.controller(...)
for both the controllers, rather than writing the variable here
Note: app.js should be loaded before any of the controllers for this to work.
This is one of the ways it can be done:
<html ng-app="myApp">
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript" src="controller1.js"></script>
<script type="text/javascript" src="controller2.js"></script>
</body>
</html>
Apart from this you can also use some task runners like gulp OR grunt to do that automatically.
If you load your app.js first, in other files you can inject your modules like
app = angular.module("myApp");
Note that I omit [] from the function call. It means that you are trying to get already defined module.

Link module from external file in AngularJS

I'm working on new project and I want to use two modules placed in separated files. Unfortunetaly, when I try to declare second in my root one I receive an error
Uncaught Error: [$injector:modulerr]
So, here is my root file, app.js:
var beerMe = angular.module("beerMe", ["admin", "ngRoute"])
.config(["$routeProvider", function($routeProvider) {
$routeProvider
.when("/home", {
templateUrl: "../views/home/home.html",
controller: "MyCtrl"
})
.otherwise({
redirectTo: "/home"
})
}])
.controller("MyCtrl", ["$scope", function($scope) {
}]);
And second one, which I want to bind, admin.js:
var admin = angular.module("admin", ["firebase", "ngRoute"]);
admin.config(["$routeProvider", function($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "views/add.html",
controller: "AdminCtrl"
}).when ("/edit", {
templateUrl: "views/edit.html",
controller: "AdminCtrl"
}).otherwise({
redirectTo: "/"
})
}]);
admin.controller("AdminCtrl", ["$scope", "$firebaseArray", function($scope, $firebaseArray) {
// my code goes here
}]);
In admin.js I connnect to firebase and I want to have access to all data from my module "beerMe".
I'd be very grateful if you could help me to figure out why there's a problem with binding these two.
Change var admin = angular.module("admin", ["firebase", "ngRoute"]);
to var admin = angular.module("admin");
and change root module like this
var beerMe = angular.module("beerMe", ["admin", "ngRoute", "firebase"])
It looks like your dependencies are the wrong way round. Having admin as a dependency of beerMe will not make the beerMe module available in your admin module.
If you want your admin module to be able to access data from inside the beerMe module then beerMe should be a dependency of admin.
var admin = angular.module('admin', ['firebase', 'ngRoute', 'beerMe']);

Angular route with $routeProvider

I'm trying to understand the routing before I start building my app but it doesn't seem to work.
I have a basic app for tests in which I created 3 html files matching 3 different views and I wish to change the displayed view depending on the routes.
But I always see the index view.
Here are the files :
app.js :
'use strict';
angular.module('BalrogApp', ['ngRoute', 'ui.bootstrap', 'BalrogApp.controllers'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: '../index.html'
})
.when('/requests', {
templateUrl: '../views/requestsList.html'
})
.when('/projects', {
templateUrl: '../views/projectsList.html'
})
.otherwise({
redirectTo: '/lol'
});
}]);
requestsController.js :
'use strict';
var requestsControllerModule = angular.module('BalrogApp.controllers', ['ngRoute', 'ui.bootstrap']);
requestsControllerModule.controller('requestsController', function($rootScope, $scope, $location, $routeParams) {
this.studentName = "Request";
this.studentMark = 75;
});
projectsController.js :
'use strict';
var projectsControllerModule = angular.module('BalrogApp.controllers', ['ngRoute', 'ui.bootstrap']);
projectsControllerModule.controller('projectsController', function($rootScope, $scope, $location, $routeParams) {
this.studentName = "Project";
this.studentMark = 75;
});
The html files are almost the same except for some words and for the controller associated to each of them.
Here are the few lines that change between html wiews :
index.html :
index view
<div class="row-fluid" ng-controller="requestsController as rc">
<div class="span2">{{rc.studentName}} </div>
</div>
requestsList.html :
Request view
<div class="row-fluid" ng-controller="requestsController as r">
<div class="span2">{{r.studentName}} </div>
</div>
projectsList.html
Project view
<div class="row-fluid" ng-controller="projectsController as p">
<div class="span2">{{p.studentName}} </div>
</div>
Byt no matter what the route is, if I added '/projects' or '/requests' to the url, I stay on the index view.
Any idea what I am doing wrong ?
Make sure you have ng-view attribute or element set in your index.html. If it is absent the router won't work.
Another good practice would be to set your view controller on the router, like so:
$routeProvider
.when('<route_name>', {
templateUrl: '../<tempate>.html',
controller: '<controller_name>',
controllerAs: 'myController'
})
1. On your base file (usually index.html), make sure you have an ng-view directive that will be used to load all the partial views
2. Are all your html templates in the same location as the base file? If yes, the instead of having the templateUrl as "../index.html" you could try setting it to "/index.html" instead. The first checks for the html file outside of the directory where the base file is located, while the second checks for it in the same directory

Controller defined in a module referenced inside a directive in another module

I have an index.html (main entry point) and I have a main.js file, say:
(function() {
var pop = angular.module('mainApp', []);
pop.directive = ('directive1', function() {
return {
restrict: 'E',
templateUrl: notIndex.html,
controller: // how to reference controller1 here? ,
controllerAs: controller1Alias
}
});
// pop.directives some more...
})();
I have a notIndex.html (template or fragment) and a corresponding controller for this html defined in notMain.js say:
(function() {
var app = angular.module('app1', []);
app.controller = ('controller1', function() {
function1...
function2...
.
.
.
functionN
});
})();
So my questions are:
How to reference controller1 in directive1 of notMain.js?
I cannot have tags in notIndex.html (it doesn't have a header or body as templates do), right? How can I reference AngularJS directives defined in notMain.js from this html? In index.html, I suppose?
Thanks for your help.
You can add app1 as a dependency of the mainApp module and it should be able to reference the controller via the controller's name. Something like this:
(function() {
var pop = angular.module('mainApp', ['app1']);
pop.directive = ('directive1', function() {
return {
restrict: 'E',
templateUrl: 'notIndex.html',
controller: 'controller1'
controllerAs: 'controller1Alias'
};
});
})();
Noticed that I changed app.directive to pop.directive? this is because app1 is not available in your mainApp closure.

Angularjs controller not found

As I felt my single controller was growing too large I am now trying to make use of multiple controllers. However, my UserController can't be found for some reason when I navigate to /signup. I'm getting this error:
Error: [ng:areq] Argument 'UserController' is not a function, got undefined
app.js
var app = angular.module('myApp', [
'ui.router',
'ngResource',
'myApp.controllers',
]);
angular.module('myApp.controllers', []);
app.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
$stateProvider
.state('signup', {
url: '/signup',
templateUrl: 'views/signup.html',
controller: "UserController"
});
});
I'm including the .js files in this order:
<script src="angular/controllers/mainCtrl.js"></script> //binded to body tag
<script src="angular/controllers/userCtrl.js"></script> //set in signup state
<script src="angular/app.js"></script>
UserController
angular.module('myApp.controllers').controller('UserController', function () {
//do stuff
});
What am I missing?
Make it easier on yourself and create cleaner code.
var app = angular.module('myApp', [
'ui.router',
'ngResource',
'myApp.controllers',
])
.config(function($stateProvider) {
$stateProvider
.state('signup', {
url: '/signup',
templateUrl: 'views/signup.html',
controller: "UserController"
});
});
you weren't using $urlRoutProvider and $httpProvider so why inject them?
Angular Modules are good for nothing...so far. Except for loading 3rd-party angular code into your app and mocking during testing. Other than that, there is no reason to use more than one module in your app.
To create your UserController do a
app.controller('UserController', function ($scope) {
//do stuff
});
<script src="angular/controllers/mainCtrl.js"></script> //binded to body tag
<script src="angular/controllers/userCtrl.js"></script> //set in signup state
<script src="angular/app.js"></script>
You cant use a module before it's declared.so switch the scripts order.
You should stick to 1 independent module declaration per file and you'll be fine,otherwise you'll have to manage script order.
Your app.js has to be declared first like below BEFORE you pull in its controller subcomponents:
<script src="angular/app.js"></script>
<script src="angular/controllers/mainCtrl.js"></script> //binded to body tag
<script src="angular/controllers/userCtrl.js"></script> //set in signup state

Categories