Angularjs Uncaught ReferenceError on injected service into directive - angularjs

Still finding my way with angular and I'm getting "Uncaught ReferenceError: y is not defined" on the line ".directive('y',[y,function(y){" . It's like it hasn't loaded the service. I also tried moving the scripts from the bod to the head but nothing do.
angular.module('fofApp', ['appRoutes'])
.factory('y',['$rootscope',function($rootScope) {
return {val: "he"};
}])
.directive('yow',[y,function(y){
return {
restrict: "E",
template: "<h1>aaaaah</h1>"
};
}]);
My html is
<!doctype html>
<html>
<head>
</head>
<body ng-app="fofApp">
<yow></yow>
<script src="libs/angular/angular.js"></script>
<script src="js/app.js"></script>
</body>
</html>

Minification protection when using dependency injection requires strings as the first arguments (to match the order/number of the parameters passing into the function), which is always the last argument.
Change that y in your directive to a string. Like so:
.directive('yow',['y',function(y){
Here's a fiddle: http://jsfiddle.net/u4v4cafm/ (no errors in console)

Not sure if this is the problem, but factory expects you to return an object. Try changing it to:
angular.module('fofApp', ['appRoutes'])
.factory('y',['$rootscope',function($rootScope) {
return { value :"he" }
}])

Related

First Angular app not outputting from controller

I'm still very new at this and this is my first attempt to making an app without following any guide. For some reason my output in the webpage is {{$scope.products}} instead of the actual values. Can anyone tell my why it won't load the angular code from the controller?
index.html
<<!doctype html ng-app="MyFirstApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainController as ctrl">
{{ctrl.name}}
{{"Hello World"}}
</body>
</html>
app.js
var app = angular.module('MyFirstApp', [])
.controller('MainController', function(){
this.name = "Joe";
});
Your snippet contains some errors:
<!doctype html ng-app="MyFirstApp"> : ngApp directive is too high. Please put it in the <body> tag at least.
ng-controller="MainController as ctrl": if it is your very first AJS example, be aware that controllerAs is a best practice, but a bit advanced. This choice will condition slightly the controller code.
{{products.title}}: products is an array!
... .controller('MainController',[$scope function($scope){: the second argument of controller method is an array, so between $scope and function a comma is needed. In your case the array must be: ['$scope',function($scope){...}]. For more info pls see https://docs.angularjs.org/guide/di
$scope.products = [...]; : in order to avoid controllerAs antipattern you must use this.products.
Please update your code.
you need to put the dependancy to your controller between '' and
you are missing some thing after $scope
.controller('MainController',['$scope',function($scope){
}]);
and there are no iterate for the array in your controller to be bind in html
var app = angular.module('MyFirstApp', [])
.controller('MainController', function(){
this.name = "Joe"
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyFirstApp" ng-controller="MainController as ctrl">
{{ctrl.name}}
</div>
AngularJS documentation can be quite confusing.
Assigning values to the $scope is considered a bad practice. This is one of the things that the controllerAs syntax solves. So instead of adding the products to $scope.products -- add them to this.name.
Then in your view you will access them with {{ctrl.name}}
I hope this helps.

Angular Scope Directives

Angular Structural Question
I am new to angular.js and am just wondering how to go about performing a certain situation.
So basically, what I have got is a container:
<div ng-controller="ContainerController">
<container></container>
</div>
And the container controller and directives.
<script type="text/javascript" src="ContainerController.js"></script>
<script type="text/javascript" src="ContainerDirectives.js"></script>
Now the directives replaces the <container> tag with an example html: <example>{{ data }}</example>
Now within the scope of the ContainerController I have defined data as a string. (This is all example purposes). However when the directive accesses replaces it, it is unable to find the variable, due to scope.
The reason that this happens is because the ContainerDirective script's scope is not within the ContainerController scope. Meaning it is unable to access the variable.
Im just not sure on structure practices for these kinds of situations. Where do I put everything so the ContainerDirective can access the ContainerController scope.
I hope i have explained everything good enough
EDIT:
Test.js
(function(){
angular.module('test', []);
})();
TestController.js
(function(){
angular
.module('test')
.controller('TestController', [
'$scope',
TestController
]);
function TestController($scope) {
$scope.test = 'test';
}
})();
TestDirective.js
(function(){
angular.module('test').directive('test', function () {
return {
replace: true,
templateUrl: 'src/test/view/test.html',
link: function (scope, element, attrs) {
}
};
});
})();
test.html
<example>ClickMe</example>
index.html - body
<body ng-app="App" layout="row" ng-controller="TestController as page">
<test></test>
<script src="src/test/Test.js"></script>
<script src="src/test/TestController.js"></script>
<script src="src/test/TestDirective.js"></script>
<script type="text/javascript">
angular
.module('App', ['test']);
</script>
</body>
For reasons I have renamed certain variables and deleted a lot of data, but this is the core, and I am struggling to see anything wrong with this.
Error: [$interpolate:noconcat] Error while interpolating: abc/{{test}}
Strict Contextual Escaping disallows interpolations that concatenate multiple expressions when a trusted value is required.
So I figured out what was wrong in the end. Basically angular wont allow iframe of another location to be printed unless you first:
Give them the full url.
Then allow external url as a trusted website.
TO do this I had to basically add:
in the Test.js
angular.module('test', []).config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist($sceDelegateProvider.resourceUrlWhitelist().concat([
'http://www.test.com/**'
]));
});
This basically took my whitelist and concatinated the new url to it.
Then inside test.html:
<example><iframe ng-src={{src}}></iframe></example>

Provider dependancy not working in Config AngularJS

My code is given below. The below code shows dependancy error when executes following code. Any help would be great. Cookies dependancies also required...
Error is
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.15/$injector/modulerr?p0=achieverpayroll&p1…A%2F%2Flocalhost%3A8080%2Fachieverpayroll%2Fjs%2Fangular.min.js%3A17%3A381)
Code app.js
(function(){
var app=angular.module('achieverpayroll',['ngRoute']);
app.provider('loginChek',function(){
this.logFn=function(){
console.log('test');
};
});
app.config(['$routeProvider', '$httpProvider','loginChekProvider', function($routeProvider, $httpProvider,loginChekProvider){
loginChekProvider.logFn();
$routeProvider.when('/home',{
templateUrl: 'templates/home.html',
controller: 'categoryController'
}).
otherwise({
redirectTo: '/home'
});
}]);
app.controller('categoryController', function($scope, $http) {
});
})();
HTML:
<!DOCTYPE html>
<html ng-app="achieverpayroll">
<head>
<meta charset="ISO-8859-1">
<META http-equiv="X-UA-Compatible" content="IE=10">
<link href="css/style.css" rel="stylesheet" type="text/css"/>
<script src="js/angular.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/angular-route.min.js"></script>
<script type="text/javascript" src="js/angular-cookies.js"></script>
<script src="js/app.js" type="text/javascript"></script>
....
Whenever you get an angular error and you could not really decode what error message means. Try to load non min version of angular and that will provide you a more descriptive error message, for example in your case you might see something like:
Uncaught Error: [$injector:modulerr] Failed to instantiate module plunker due to:
Error: [$injector:pget] Provider 'loginChek' must define $get factory method.
Which is very evident that your provider does not have a service constructor associated with it. It just defines a provider function that can be accessed during the config phase which is not enough. For example:
app.provider('loginChek',function(){
var loggedIn = false;
//This is accessible only during the config phase before the
//service loginCheck is even instantiated
this.logFn=function(){
loggedIn = true;
console.log('test');
};
//When you inject loginCheck anywhere else you will get a service instance
//with one method hasLoggedIn
this.$get = function(){
return {
//You can inject services stuffs here like
//hasLoggedIn:function($http, $q...)
hasLoggedIn:function(){
return loggedIn;
}
}
}
});
plnkr
Doc says:
You should use the Provider recipe only when you want to expose an API for application-wide configuration that must be made before the application starts. This is usually interesting only for reusable services whose behavior might need to vary slightly between applications.
Provider method logFn cannot really make use of any services because the services are not instantiated yet (for example you cannot inject $http service directly in a provider function, i.e .provider('loginChek',function($http){), but you can inject other providers as you need. So they are generally used only for simple configuration for your service.
Try declaring your provider like this:
app.provider('loginChek',function(){
this.$get = function(){
return {
logFn: function() { console.log('test') }
};
};
});
This error occurs when a module fails to load due to some exception.
Have you installed the ngRoute module?
https://code.angularjs.org/1.3.15/docs/api/ngRoute

Can't attach angularjs service to controller

I'm getting this error when I try to attach a service to a controller:
[$injector:unpr] ... webSocketServiceProvider <- webSocketService <- videoMenuCtrl
I have a plunker defined with a fairly minimal setup that reproduces the problem:
http://plnkr.co/edit/ptaIaOhzOIG1mSi4bPyF?p=preview
Here are the main culprit files:
index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>title</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-app="videoApp">
<section class="menu" ng-controller="videoMenuCtrl">
</section>
<script src="webSocketService.js"></script>
<script src="videoMenu.js"></script>
<script src="ngDialog.min.js"></script>
<script src="ngPopup.min.js"></script>
</body>
</html>
webSocketService.js:
(function(angular) {
'use strict';
angular.module('videoApp')
.factory('webSocketService', function($q) {
return{};
});
});
videoMenu.js:
'use strict';
var app = angular.module('videoApp', ['ngDialog', 'ngPopup']);
app.controller('videoMenuCtrl', function($scope, $window, $location, ngDialog, webSocketService) {
});
I don't get an error if I remove the webSocketService from the controller, but the point is to have the controller be able to access the webSocketService. Any ideas? Thanks!
Edit: Changed file name typo.
I got your code working. Two things I noticed:
In you webSocketService.js you were re-declaring the videoApp module.
You were declaring the module inside a function expression that was not being invoked.
I re-declared your service in a properly namespaced module and wrapped it in an immediately invoked function expression.
I also removed your var app = declaration from your videoMenuCtrl and wrapped it in an IIFE as well. This is to avoid cluttering the global namespace. Here is a working plunk:
http://plnkr.co/edit/A8BcATiaqhXCA7BZDXWx?p=preview
EDIT (clarification) The IIFEs are not strictly necessary in my example plunk because the var app = declaration was removed from the code. That was the only variable that was being declared on the global namespace in the original example. However, wrapping the code in IIFEs has no negative effects as far as I know.

Argument 'PricesController' is not a function, got undefined

I have looked at a lot of examples related to setting up the app, and everything I'm doing seems correct but I'm still getting the error above. Here's my setup.
_Layout.cshtml
<!DOCTYPE html>
<html data-ng-app="homePricesApp">
<head>
<script src="libs/angular.1.0.8.min.js"></script>
<script src="controllers.js"></script>
<title></title>
</head>
<body >
<div data-ng-controller="PricesController"></div>
</body>
</html>
controllers.js
var app = angular.module("homePricesApp", []);
app.controller('PricesController', ['$scope', function ($scope) {
$scope.items = [];
} ]);
So what I'm doing is creating a new homePricesApp module, and when the page is loaded, because I have data-ng-app="homePricesApp", it initializes the homePricesApp module. I then create the controller. But when the page loads I get the error:
"Argument 'PricesController' is not a function, got undefined".
Any ideas would be greatly welcome.
UPDATE
After much reading I came across the idea of manually bootstrapping the app using the code below, which worked, as in it now hits my controller, but the error is being thrown by angular.js before it hits the controller code.
angular.element(document).ready(function() {
angular.bootstrap(document.getElementById('pricesResults'), ['homePricesApp']);
});
Your code works for me.
Your angular is loaded correctly? try this
https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js

Resources