Service not in scope from within an Angular event handler - javascript

I've decided to learn Angular.js after having learned JavaScript and jQuery and am finding the going a bit rough. Here's my code.
index.html:
<html>
<head>
<title>Resolute</title>
<script src="js/angular 1.3.0-beta9/angular.js" type="text/javascript"></script>
<script src="js/index.js" type="text/javascript"></script>
</head>
<body ng-app="resoluteApp">
<form novalidation ng-controller="resoluteCtrl" ng-submit="submit()">
<button type="submit">Submit</button>
</form>
</body>
</html>
index.js:
var app = angular.module('resoluteApp', []);
app.service('resoluteService', function myService() {
this.bar = function() { return 'resolute'; };
});
app.controller('resoluteCtrl', function($scope) {
$scope.submit = function() {
alert(resoluteService.bar()); // resoluteService is undefined here
};
});
I would like to be able to call the function bar() defined in the service resoluteService from within the ng-submit event handler $scope.submit(). Upon pressing the Submit button, I get the following error (Chrome 35.0.1916.153) in the console:
ReferenceError: resoluteService is not defined
at Scope.$scope.submit (http://localhost:8383/resolute/js/index.js:9:19)
at http://localhost:8383/resolute/js/angular%201.3.0-beta9/angular.js:10797:21
at http://localhost:8383/resolute/js/angular%201.3.0-beta9/angular.js:19791:17
at Scope.$eval (http://localhost:8383/resolute/js/angular%201.3.0-beta9/angular.js:12699:28)
at Scope.$apply (http://localhost:8383/resolute/js/angular%201.3.0-beta9/angular.js:12797:23)
at HTMLFormElement.<anonymous> (http://localhost:8383/resolute/js/angular%201.3.0-beta9/angular.js:19790:21)
at http://localhost:8383/resolute/js/angular%201.3.0-beta9/angular.js:2860:10
at forEach (http://localhost:8383/resolute/js/angular%201.3.0-beta9/angular.js:327:20)
at HTMLFormElement.eventHandler (http://localhost:8383/resolute/js/angular%201.3.0-beta9/angular.js:2859:5)
As I'm still trying to get my head wrapped around the Angular way of doing things, I am not sure how to direct either resoluteService or the function bar within it to be in scope of $scope.submit. It may be I'm thinking about it in entirely the wrong way, or it may just be something simple I'm missing. Any thoughts as to how I can resolve this?

You need to inject the service in to controller ,
app.controller('resoluteCtrl', function($scope,resoluteService) {
}

Related

Issue with angular-route.min.js | Error Chrome Console [$injector:modulerr]

!!Total beginner here!!
I have run into an error - chrome console gives me an error regarding:
[$injector:modulerr]
The problem is that I have not installed angular-route.min.js which is what you're supposed to do in all angular versions after 1.2. My trouble began when I installed angular-route.min.js, put it in the same file as angular and my HTML files, referenced it in the code with <script src="angular-route.min.js"></script> but nothing happened.
I also put angular.module('app.js', ['ngRoute']); into my js file.
There are no typos in my code, I checked for those. On top of all that the console gives me an error saying angular-route.min.js was not found.
All help welcome, I have spent a long time googling but nothing came of it.
(function () {
'use strict';
angular.module('MSgApp', []);
controller:('MsgController', MsgController);
angular.module('app.js', ['ngRoute']);
MsgController.$inject = ['$scope'];
function MsgController($scope) {
$scope.name = "Chris";
$scope.stateOfBeing = "hungry";
$scope.sayMessage = function () {
return "chris likes to eat cookies";
};
$scope.feedChris = function () {
$scope.stateOfBeing = "fed";
};
}
})();
<!DOCTYPE html>
<html ng-app='DIApp'>
<head>
<meta charset="utf-8">
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="app.js"></script>
<title>custom attributes</title>
</head>
<body>
<div ng-app="app.js"></div>
<h1>expressions and interpolation</h1>
<div ng-controller='MsgController'>
{{name}} has a message for you: <br>
{{sayMessage()}}
<div>
<button ng-click="feedChris()">Feed chris</button>
<br>
<img ng-src="D:/stuff/coursera angular/chris_{{stateOfBeing}}.png">
</div>
</div>
</body>
</html>
Errors after unminified both angular and angular-route
As per StackOverflow --> Angular JS Uncaught Error: [$injector:modulerr]:
EDIT: This is what ultimately solved the issue and what Chris B did to make it work :
I have come across another code in the Coursera course and this one seems to be working after putting the three links from the answer by #ulmer-morozov into the head tag instead of referencing files on my pc. I guess that's it,
From Answer of #ulmer-morozov:
In development environments I recommend you to use not minified distributives. And all errors become more informative! Instead of angular.min.js, use angular.js.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.js">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.js">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.js">
From Accepted Answer #Lauri Elias:
Try adding this:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.min.js"></script>
From Answer of #Khanh TO:
Try adding:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.min.js">
and:
angular.module('MyApp', ['ngRoute','ngResource']);
function TwitterCtrl($scope,$resource){
}
You should call angular.module only once with all dependencies because with your current code, you're creating a new MyApp module overwriting the previous one.
From angular documentation:
Beware that using angular.module('myModule', []) will create the
module myModule and overwrite any existing module named myModule. Use
angular.module('myModule') to retrieve an existing module.

How to use scope variables in attributes with string

I am new in angularjs. I have a issue scope variable not working in script tag. I had try ng-src but still not working.
script_path variable not working with script.js if I add only {{script_path}} working fine but if I add {{script_path}}/script.js this is not working.
My example code
<html ng-app="myApp">
<head ng-controller='HeadCn'>
<meta charset="utf-8">
<title>test</title>
<script src="js/angular.js"></script>
<script ng-src="{{script_path}}/script.js"></script>
</head>
<body class="container">
<script>
var app = angular.module('myApp', []);
app.controller("HeadCn", function($scope) {
$scope.script_path = "js/";
})
</script>
</body>
</html>
please give me solution how to use scope variable anywhere in controller.
Thanks in advance
Jimbrooism is right, you are getting this error because security concerns are not being handled.
Please read carefully at https://docs.angularjs.org/api/ng/service/$sce
You may need to use other filter as described on that page or you can completely disable sce at config level, which not recommended
use $sce resolve the problem, create a filter for solve this problem
angular.module('myApp')
.filter('trustUrl', function ($sce) {
return function(url) {
return $sce.trustAsResourceUrl(url);
};
});
<script ng-src="{{script_path}}/script.js | trustUrl "></script>

Angularjs: Error: [ng:areq] Argument 'HomeController' is not a function, got undefined

This is my demo using angularjs, for creating a service file, and adding service to a controller.
I have two problems with my demo:
One is when I put <script src="HomeController.js"> before <script src="MyService.js"> I get this error,
Error: [ng:areq] Argument 'HomeController' is not a function, got undefined
The other is when I put <script src="MyService.js"> before <script src="HomeController.js"> I get the following error,
Error: [$injector:unpr] Unknown provider: MyServiceProvider <- MyService
My source:
File Index.html:
<!DOCTYPE html>
<html >
<head lang="en">…</head>
<body ng-app="myApp">
…
<div ng-controller="HomeController">
<div ng-repeat="item in hello">{{item.id + item.name}}</div>
</div>
<script src="Scripts/angular.js"></script>
<script src="Scripts/angular-route.js"></script>
<!-- App libs -->
<script src="app/app.js"></script>
<script src="app/services/MyService.js"></script>
<script src="app/controllers/HomeController.js"></script>
</body>
</html>
File HomeController.js:
(function(angular){
'use strict';
var myApp = angular.module('myApp',[]);
myApp.controller('HomeController',function($scope,MyService){
$scope.hello=[];
$scope.hello = MyService.getHello();
});
})(window.angular);
File MyService.js:
(function(angular){
'use strict';
var myApp = angular.module('myApp',[]);
myApp.service('MyService', function () {
var hello =[ {id:1,name:'cuong'},
{id:2,name:'nguyen'}];
this.getHello = function(){
return hello;
};
});
})(window.angular);
This creates a new module/app:
var myApp = angular.module('myApp',[]);
While this accesses an already created module (notice the omission of the second argument):
var myApp = angular.module('myApp');
Since you use the first approach on both scripts you are basically overriding the module you previously created.
On the second script being loaded, use var myApp = angular.module('myApp');.
I experienced this error once. My problem was that I wasn't adding the FILE_NAME_WHERE_IS_MY_FUNCTION.js
so my file.html never found where my function was
Once I add the "file.js" I resolved the problem
<html ng-app='myApp'>
<body ng-controller='TextController'>
....
....
....
<script src="../file.js"></script>
</body>
</html>
Also ensure that your controllers are defined within script tags toward the bottom of your index.html just before the closing tag for body.
<!-- build:js({.tmp,app}) scripts/scripts.js -->
<script src="scripts/app.js"></script>
<script src="scripts/controllers/main.js"></script>
<script src="scripts/controllers/Administration.js"></script>
<script src="scripts/controllers/Leaderboard.js"></script>
<script src="scripts/controllers/Login.js"></script>
<script src="scripts/controllers/registration.js"></script>
provided everything is spelled "correctly" (the same) on your specific.html, specific.js and app.js pages this should resolve your issue.
Happened to me few times whenever I miss "," between list of injections and function
app.controller('commonCtrl', ['$scope', '$filter',function($scope,$filter) {
}]);
I also experienced this error but in my case it was because of controller naming convention. I declared controller: "QuestionController" in .state but in controller definition I declared it like
yiiExamApp.controller('questionController' ...
but it should be
yiiExamApp.controller('QuestionController' ...
hope that helps to people facing this error because of this stupid mistake I wasted 4hour in identifying it.
I also encountered this same error and the fix for me was to include my child module in the main module array.
var myApp = angular.module('myApp', ['ngRoute', 'childModuleName']);
If ALL ELSE fails and your running locally on the MEAN stack like me with gulp...just stop and serve again! I was pulling my hear out meticulously checking everything from all of your posts to no avail till I simply re-ran gulp serve.
I got the same error. I defined java script like this
<script src="controllers/home.js" />
then I changed to the this
<script src="controllers/home.js"></script>
After this my problem is solved.
I had similar issue. The fix was ensure that your ctrollers are not only defined within script tags toward the bottom of your index.html just before the closing tag for body but ALSO validating that they are in order of how your folder is structured.
<script src="scripts/app.js"></script>
<script src="scripts/controllers/main.js"></script>
<script src="scripts/controllers/Administration.js"></script>
<script src="scripts/controllers/Leaderboard.js"></script>
<script src="scripts/controllers/Login.js"></script>
<script src="scripts/controllers/registration.js"></script>
I also encountered this problem in my project. It eventually worked after I inserted the my-controller.js into my karma.conf.js file, with the <script> tag.
Hope this will help. There are quite many reasons that can lead to this problem.
I also got this error.
I had to add my new controller to routing information.
\src\js\app.js
angular.module('Lillan', [
'ngRoute',
'mobile-angular-ui',
'Lillan.controllers.Main'
])
I added my controller to make it look like
angular.module('Lillan', [
'ngRoute',
'mobile-angular-ui',
'Lillan.controllers.Main',
'Lillan.controllers.Growth'
])
Cheers!
Obviously that previous posts are useful, but any of above are not helpful in my case. The reason was in wrong sequence of loading scripts. For example, in my case, controller editCtrl.js depends on (uses) ui-bootstrap-tpls.js, so it should be loaded first.
This caused an error:
<script src="scripts/app/station/editCtrl.js"></script>
<script src="scripts/angular-ui/ui-bootstrap-tpls.js"></script>
This is right, works:
<script src="scripts/angular-ui/ui-bootstrap-tpls.js"></script>
<script src="scripts/app/station/editCtrl.js"></script>
So, to fix the error you need first declare all scripts without dependencies, and then scripts that depends on previously declared.
Try this
<title>My First Angular App</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<h3>Adding Simple Controller<h3>
<div ng-controller="SimpleController">
Name:
<br/>
<input type = "text" data-ng-model = "name"/> {{name}}
<br/>
<ul>
<li data-ng-repeat = "cust in customers | filter:name | orderBy:'city'">
{{cust.name}} - {{cust.city}}
</li>
</ul>
</div>
<script>
var angularApp = angular.module('angularApp',[]);
angularApp.controller('SimpleController', [ '$scope', SimpleController]);
function SimpleController($scope)
{
$scope.customers = [
{name:'Nikhil Mahirrao', city:'Pune'},
{name:'Kapil Mahire', city:'Pune'},
{name:'Narendra Mahirrao', city:'Phophare'},
{name:'Mithun More', city:'Shahada'}
];
}
</script>
</body>
In my case, I was missing the name of the Angular application in the html file. For example, I had included this file to be start of my application code. I had assumed it was being ran, but it wasn't.
app.module.js
(function () {
'use strict';
angular
.module('app', [
// Other dependencies here...
])
;
})();
However, when I declared the app in the html I had this:
index.html
<html lang="en" ng-app>
But to reference the Angular application by the name I used, I had to use:
index.html (Fixed)
<html lang="en" ng-app="app">
I was getting the error because i had added the controller script before the script where i had defined the corresponding module in the app.
First add the script
<script src = "(path of module.js file)"></script>
Then only add
<script src = "(path of controller.js file)"></script>
In the main file.
Error: ng:areq Bad Argument has gotten me a couple times because I close the square bracket too soon. In the BAD example below it is closed incorrectly after '$state' when it should actually go before the final parenthese.
BAD:
sampleApp.controller('sampleApp', ['$scope', '$state'], function($scope, $state){
});
GOOD:
sampleApp.controller('sampleApp', ['$scope', '$state', function($scope, $state){
}]);
Yes. As many have previously pointed out,
I have added the src path to all the controller files in the index.html.
<script src="controllers/home.js"></script>
<script src="controllers/detail.js"></script>
<script src="controllers/login.js"></script>
<script src="controllers/navbar.js"></script>
<script src="controllers/signup.js"></script>
This fixed that error.
I had the same problem, but I forgot to include the file into grunt/gulp minimization process.
grunt.initConfig({
uglify: {
my_target: {
files: {
'dest/output.min.js': ['src/input1.js', 'src/missing_controller.js']
}
}
}
});
Hope that helps.
In my situation this error appeared when I didn't declare function within an array argument.
The one with error:
taskAppControllers.controller('MainMenuCtrl', []);
The fixed one:
taskAppControllers.controller('MainMenuCtrl', [function(){
}]);
Also check for spelling mistakes.
var MyApp = angular.module('AppName',[]);
MyApp.controller('WRONG_SPELLING_MyCtrl', ['$scope', MyControllerCtrl])
function MyControllerCtrl($scope) {
var vm = $scope;
vm.Apple = 'Android';
}
<div ng-controller="ACTUAL_SPELLING_MyCtrl">
{{Apple}}
</div>
Check if your HTML page includes:
angular.min script
app.js
controller JavaScript page
The order the files are included is important. It was my solution to this problem.
Hope this helps.
sampleApp.controller('sampleApp', ['$scope', '$state', function($scope, $state){
Same thing for me, comma ',' before function helped me in fixing the issue -- Error: ng:areq Bad Argument
My controller file was cached as empty. Clearing the cache fixed it for me.
I accidentally moved my HomeController.js out of the directly, where it was expected.
Putting it again on original location.
After that my website started to load pages automatically every second, I was even unable to look at the error. So i cleared the browser cache. It solved the problem
For me the solution was to add a semicolon after one of the functions declared in my HomeController.js
//Corrected code is :
app.controller('HomeController', function($scope, $http, $log) {
$scope.demo1 = function(){
console.log("In demo");
} //Here i forgot to add the semicolon
$scope.demo2 = function(){
console.log("In demo");
};
});

AngularJS private variable in controller function

I am new to Angularjs. I came across a example online and it got me really confused. Here is the code:
angular.module("testApp",[]).controller("testCtrl", function($scope){
var data = "Hello";
$scope.getData = function(){
return data;
}
$scope.setData = function(newData){
data = newData;
}
});
Here is the view:
<html ng-app = "testApp">
<head>
<script src="lib/Angular.js"></script>
<script src = "foo.js"></script>
</head>
<body ng-controller="testCtrl">
<div ng-click="setData('Hello Hello')">{{getData()}}</div>
</body>
</html>
My question is how does angular know when to trigger the getData() method in the view. The click event will change the data. However its a private variable, not attaching to the $scope, which means $scope does not watch the change of it, then how does angular know when to call the getData() in the view? I know it maybe a dumb question, but please help! thank you so much!!
The double-curly expression is what AngularJS calls an observing directive. During the compilation phase, this directive registers listeners on the expression using the $watch method of the scope.
On the other hand, ng-click is what AngularJS calls a listener directive. This type of directive registers a listener with the DOM instead. Whenever the DOM event fires, the directive executes the associated expression inside an $apply call.
This means that after the click expression is executed, a $digest cycle will begin. In this cycle, the scope examines all the registered $watch expressions (e.g. the double-curly expression containing getData()) and calls the listener in case there's a difference from the previous value.
In the end, it is this digest cycle that ensures that all your bound expressions are evaluated.
The top level controller function runs immediately before it renders the view, in order to initialise the scope. Next the view loads and any logic in the view executes. So when it reaches getData() it returns the output of that function at that time.
The clever part is that Angular automatically binds the data in your views all the way back to the data model, so whenever there is a change in the model (i.e. the source of the data) that automatically updates the value in the view and if necessary will run your getData() method several times.
I saved it here as a Plnkr
Your binding {{getData()}} is a "run on evaluation". So when the DOM renders and angular parses it, it sees the () at the end and runs the function. I'll provide citation in a minute when I find it.
You don't need the getData in angularjs ... or maybe for other uses than the one you are showing right there.
So the right code would be (without getData) :
<html ng-app = "testApp">
<head>
<script src="lib/Angular.js"></script>
<script src = "foo.js"></script>
</head>
<body ng-controller="testCtrl">
<div ng-click="setData('Hello Hello')">{{data}}</div>
</body>
</html>
And with getData :
$scope.getData = function(){
data = 'Hello World';
}
<html ng-app = "testApp">
<head>
<script src="lib/Angular.js"></script>
<script src = "foo.js"></script>
</head>
<body ng-controller="testCtrl">
<div ng-init="getData()" ng-click="setData('Hello Hello')">{{data}}</div>
</body>
</html>

Dojo function called in HTML

my html:
<html>
<head>
<script src="dojo/dojo.js"></script>
<script src="app/my.js"></script>
<script>
handleResult(<%server response data%>);
</script>
</head>
<body>
<div id="data"></div>
</body>
</html>
my js:
require(["dojo/_base/Array"],function(Array){
handleResult = function(data){
Array.forEach(data,function(item,index){
//Process the data
});
}
});
When the page loads call handleResult, I get an error:
Uncaught ReferenceError: test is not defined
But I can get this function in firebug
window.handleResult
please help me .thank.
Do NOT use onclick, please.
require(["dojo/on", "dojo/dom"],function(dom) {
var button = dom.byId("demo"));
on(button, "click", function(evnt) {
console.log(evnt);
})
});
The require function is asynchronous. You cannot define a global variable from inside a require callback and then try to immediately access it. You should also never define globals to begin with, this is one of the basic tenets of AMD. Your application architecture is wrong and will never work. You need to use an AJAX call to request the “server response data” once the application is loaded on the client, and not try to do what you are doing.

Categories

Resources