Yeoman Angularjs How to Implement Directive - javascript

I'm trying to get my feet off the ground with Yeoman + Angular and going through the tutorials, I can't get even the most basic directives to fire, even when I try them exactly the same as in the tutorials.
Could someone please lend some insight as to what I'm missing, I've been struggling with this for the past 2 days
HTML template - ng-resize is the intended directive
<body ng-app="mvmdApp">
....
<div ng-mousemove="onMouse($event)" ng-resize="" class="youtube-cover ng-scope">
<div class="youtube-unit"></div>
</div>
// controllers/youtube.js
'use strict';
angular.module('mvmdApp').controller('YoutubeCtrl', function($scope) {
console.log('hi');// fires
return $scope.onMouse = function(e) {}// fires
// directives/resize.js
'use strict';
angular.module('mvmdApp', []).directive('ngResize', function($window) {
return function(scope) {
return console.log('directive');// does not fire
};
});
The strange thing is that whenever I even call angular.module('mvmdApp', []) like so from the directive script, it blocks the view from rendering.
edit: Also I noticed that when I load the directive before all the other scripts, it doesn't block the html from rendering, but it still doesn't trigger the directive. I don't know if/how the load order of angular scripts matters as I don't know where to find that.

You are declaring the module multiple times. You can simplify this by doing the following:
In app.js:
'use strict';
var myApp = angular.module("mvmdApp", []);
myApp.config(function($routeProvider, $locationProvider) {
...
});
In youtube.js:
'use strict';
myApp.controller('YoutubeCtrl', function($scope) {
...
});
An in resize.js:
'use strict';
myApp.directive('resize', function($window) {
...
});
Updated plunker at http://plnkr.co/edit/Im4SpcyH4cIem6TDWZaG?p=preview. Also, I would refrain from calling the directive "ng-resize" as the ng prefix is usually used by the angular team. In this case, the directive is simply "resize".

This may not solve your issue but one mistake i see is
angular.module('mvmdApp', []) been declared at multiple places, resize.js and app.js. This format declaration creates a new module everytime with this name.
This should be called once only from app.js. In resize.js it should be angular.module('mvmdApp')

Related

Angular: [$injector:modulerr] Failed to instantiate module

I've been trying to set up basic AngularJS functionality for a project but have been hitting a brick wall when it comes to including angular-route. Both are version 1.4.8. I'm currently using gulp-require to concatenate my JS, here's my main javascript file
// =require ../components/jquery/dist/jquery.min.js
// =require ../components/angular/angular.js
// =require ../components/angular-route/angular-route.js
$(document).ready(function() {
// =require app/app.js
}); // Doc ready is done!
And my app.js file
var app = angular.module('myApp', ['ngRoute']);
app.controller("ctrl", ["$scope", 'ngRoute', function($scope) {
$scope.test = "It works!";
}]);
I've checked and all the files are concatenating properly. The ng-app and ng-controller attributes are on my HTML file. I've tried adding and removing the ngRoute injection and switching the order of the files but to no avail. It's frustrating since I used Angular 1.4.5 in almost the exact same way without these issues popping up but I can't replicate the same here even when going back. But the {{test}} variable in my HTML is still not rendering, and basic operations like {{2 + 3}} aren't either.
EDIT: here is the link to the original error message I'm currently receiving: http://tinyurl.com/zx3k85f
EDIT 2: The parts of my HTML code that's calling the app and the controller:
<html lang="en" ng-app="myApp">
<body ng-controller="ctrl">
</body>
</html>
I'm using nunjucks for HTML dynamic generation, although I've changed the syntax for this so it doesn't conflict with Angular's double curly braces.
You can't inject module as dependency inside controller, you should remove 'ngRoute' from the controller DI inline array.
app.controller("ctrl", ["$scope", , function($scope) {
Update
Basically the real problem is you are loading your angular component script using requirejs(lazily), so while you are having ng-app="myApp" with module name start looking for myApp module, and the module has not loaded therefore it throws an error .
So I'd recommend you to don't use ng-app directive to start angular on page load. Instead you should wait until all the scripts related to angular loaded, & then to bootstrap angular app lazily using angular.bootstrap method.
Code
$(document).ready(function() {
requirejs(["app/app.js"], function(util) {
angular.bootstrap(document, ['myApp']);
});
});
ngRoute is a provider that needs to be configured in the module config section before being used. Using it within a controller does not make any sense. Here the version that will work:
angular.module('myApp', ['ngRoute']);
angular.module('myApp').controller("ctrl", ["$scope",function($scope) {
$scope.test = "It works!";
}]);
Moreover, you need to call your module using directive ng-app=myapp in the html element where you plan to render your app.

Why controllers is being created 2 times in my AngularJS + RequireJS application?

I am creating small application called puzometr. It is for educational needs only. I want to create this application using AngularJS. Also, I want to use RequireJS as module system.
I have strange problem. I created my test controller and I got problem: controller initialization fires two times.
Firstly, full code available here on GitHub (wait, don't click me, I will explain everything below).
So, problem is in myCtrl.js file. Here is code of this file:
define(['angular'], function (angular) {
var module = angular.module('main.myModule', []);
module.controller('main.myCtrl', function ($scope) {
console.log($scope.$id);
$scope.bob = function () {
}
})
});
It is included in main/controllers/controllers.js by this:
define(['app', 'main/controllers/myCtrl'], function (app) {
var module = angular.module('main.controllers', ['main.myModule']);
});
This file included in main.js by this code:
angular.module('main', ['ngRoute', 'main.services', 'main.controllers', 'main.directives']);
And main.js is included into app.js:
var app = angular.module('myApp', ['ngRoute', 'main', 'common']);
So, I incidentally noticed, that function definition in myCtrl controller fired two times. I put console.log there and saw this:
Can you please explain me why is this happens? Why controller is being initialised two times?
Also, I have this in ng-inspector:
So one scope is created as child for another scope. Notice, that scope with id 3 has correct controller name.
If you use ng-route to register controllers and bind them with views, then don't add them again using attributes in your html files.

Angularjs: inject Controller on module inside anonymous function

I am a bit newbiew with javascript and i am starting to use angular.js
So my question is if there is a way to inject a controller inside a module that is declared in an anonymous function
my code looks like this
app.js
(function(angular) {
var app = angular.module('Organizer', ['ngMaterial', 'ngAnimate', 'ngAria']);
})(angular);
siteController.js
(function(angular, app) {
app.controller('site', function($scope, $mdDialog)
{
var alert = $mdDialog.alert({
title: 'Test',
content: 'Testing',
ok: 'Exit'
});
$mdDialog.show(alert);
});
})(angular);
i have tried to look for ways if it is possible, but still i would like to see if anyone here could explain how this can be made if it could.
Note: I have already used angular.js before and i wanted to try a different way to declare controllers so the client wont have any way to modify it
If you create a module in Angular, then you can not obfuscate it in this way. In the console, a user can just run angular.module('Organizer') to get access to your app, and then call any method they want on it.
The reason your code won't work as written, is because you are not passing the app variable to your anonymous function. So if you want to add a controller to the Organizer module, then you would do something like this:
(function(angular)
{
angular.
module('Organizer').
controller('site', function($scope, $mdDialog)
{
...
});
})(angular);
Theres no need to wrap any of this code in self executing functions as if you are trying to keep variables out of the global scope. The only one that's global is the "angular" object.
Your app.js should only have
'use strict';
angular.module('Organizer', ['ngMaterial', 'ngAnimate', 'ngAria']);
You controller file should only have
'use strict';
angular.module('Organizer').controller('siteController', function($scope, $mdDialog) {
var alert = $mdDialog.alert({
title: 'Test',
content: 'Testing',
ok: 'Exit'
});
$mdDialog.show(alert);
});
The first call to module in app.js passes the second parameter which angular uses to instantiate your module. Subsequent calls that omit the second parameter "get" the module.

$injector unable to resolve required dependency

I'm trying to get into the habit of structuring my Angular projects following LIFT protocol (Locate, Identify, Flat, Try(Dry)) but I'm having some difficulty resolving dependencies from other files.
I have the following factory:
(function () {
'use strict';
angular
.module('CBPWidget', [])
.factory('apiManufacturers', apiManufacturers);
function apiManufacturers () {
function hello () {
return 'hello';
}
return {
hello: hello
};
}
})();
and the following controller:
(function () {
'use strict';
angular
.module('CBPWidget', [])
.controller('stepOneController', stepOneController);
stepOneController.$inject = ['$scope', 'apiManufacturers'];
function stepOneController ($scope, apiManufacturers) {
$scope.step = 'step1';
console.log(apiManufacturers.hello);
}
})();
and the following error is thrown:
Error: [$injector:unpr] Unknown provider: apiManufacturersProvider <- apiManufacturers <- stepOneController
My factory JS file is placed above the controller JS file in my HTML (which will be minified).
Any advice on where I'm going wrong would be greatly appreciated as I'm new to structuring projects this way.
Here you are creating CBPWidget module two times.
angular.module('CBPWidget',[]) is used for creating module and
angular.module('CBPWidget') is used for getting already created module.
so replace controller code with this :
(function () {
'use strict';
angular
.module('CBPWidget')//now you are getting CBPWidget module
.controller('stepOneController', stepOneController);
stepOneController.$inject = ['$scope', 'apiManufacturers'];
function stepOneController ($scope, apiManufacturers) {
$scope.step = 'step1';
console.log(apiManufacturers.hello);
}
})();
Your angular.module('CBPWidget', []) block code is redefining angular app, which was flushing apiManufacturers service associated with it, & it is defining controller in it. You should never do that, you should use existing module which was already defined.
Code
angular
.module('CBPWidget') //don't overide app here use existing
.controller('stepOneController', stepOneController);
From the documentation for AngularJS, you'll find that
.module('CBPWidget', [])
is different from
.module('CBPWidget')
The latter is what you need to refer to a module, the former is for defining one. In all cases except where you first define it, you should be using the latter form.

AngularJS Injector - Error: [$injector:unpr] Unknown provider: $rootScopeProvider <- $rootScope

May be it's trivial question, but for AngularJS newbie it's a matter ^_^
What I'm trying to originally achieve is to make a dynamically inserted tag (by jQuery) with ng-click directive to work. I've searched and found that I've to get AngularJS Injector, then compile that code. So here it is the simplest form of the injector code which is NOT working for me, what's wrong with it?
Note #1: The dynamically inserted tag with ngDirective is done outside AngularJS scope.
angular.module('simpleExample', [])
.run(
[ '$rootScope',
function ($rootScope) {
$rootScope.test = "Test";
}]);
console.log(angular.injector(['simpleExample']));
// console.log(angular.injector(['simpleExample']).$compile('Text'));
http://jsfiddle.net/Zx8hr/6/
The ng module
angular.bootstrap automatically adds the ng module to the dependencies when used (manually or with ngApp)
$rootScope / $compile services are part of the ng module.
You need to use injector.invoke if you want these services.
You should probably use angular in more traditional ways.
Try this:
angular.module('simpleExample', ['ng']);
angular.injector(['simpleExample'])
.invoke(['$rootScope','$compile',
function($rootScope, $compile){
var elm = $compile('Text')($rootScope);
$rootScope.someFunctionOnRootScope = function(){
alert("Hello there!");
}
angular.element(document.body).append(elm);
}]);

Categories