How to use scope variables in attributes with string - javascript

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>

Related

Angular js script is not executing [duplicate]

I am learning Angular.js and I am not able to figure out whats wrong with this simple code. It seems to look fine but giving me following error.
**Error**: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.14/$injector/modulerr?p0=app&p1=Error%3A%20…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A17%3A381)
And before adding ng-app="app" (I was just keeping it as ng-app) it was giving me following errors. Why is that?
Error: [ng:areq] http://errors.angularjs.org/1.3.14/ng/areq?p0=Ctrl&p1=not%20a%20function%2C%20got%20undefined
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:6:417
at Sb (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:19:510)
at tb (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:20:78)
at $get (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:75:331)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:57:65
at s (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:7:408)
at A (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:56:443)
at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:51:299)
at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:51:316)
<!doctype html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<div ng-controller="Ctrl">
<input ng-model="name">
<h1>{{name}}</h1>
<h2>{{age}}</h2>
</div>
<script>
var Ctrl = function($scope)
{
$scope.age = 24;
};
</script>
</body>
</html>
After AngularJS version 1.3 global controller function declaration is disabled
You need to first create an AngularJS module & then attach all the components to that specific module.
CODE
function Ctrl($scope) {
$scope.age = 24;
}
angular.module('app', [])
.controller('Ctrl', ['$scope', Ctrl]);
Specifically for your case, there is some issue with AngularJS 1.3.14 (downgrade it to 1.3.13 works fine). Though I'd prefer you to use angular 1.2.27 AngularJS 1.6.X, Which is more stable version & latest release of AngularJS.
Working Plunkr
UPDATE:
You could do your current code to working state by allow global controller declaration inside angular.config. But this isn't the correct way to run angular application.
function Ctrl($scope) {
$scope.age = 24;
}
angular.module('app', [])
.config(['$controllerProvider',
function ($controllerProvider) {
$controllerProvider.allowGlobals();
}
]);
I was myself stuck in this issue for sometime. Check for following in order:-
The path to you angular.js script is correct (whether you are calling it in your HTML from a local source or as an external resource).
Next, once your angular.js is correct check if your app is initialized or not.
var app=angular.module('app',[])//in your app.js file
<body ng-app="app">//in your html
Next register your controller with the app and pass in all necessary injections
app.controller('myCtrl',function(){});
Call your javascript file in your html file
<script src="app.js"></script>
You have to define your controller
var app = angular.module('app', []);
app.controller('Ctrl', ['$scope',function($scope) {
$scope.age = 24;
}]);
Be Sure that ng-app="app_name" define must match to
var app=angular.module('app_name',[])
<html ng-app="myApp">
<body>
<div ng-controller="Ctrl">
<input ng-model="name">
<h1>{{name}}</h1>
<h2>{{age}}</h2>
</div>
<script>
var app = angular.module('myApp',[]); // same to the above define appName
app.controller('Ctrl',function($scope){
$scope.age=24; // initialize age by injecting scope
});
</script>
</body>
<html>
For more details visit Here
Check the version of angularjs in your html file.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
Call your javascript file in your HTML file
<script src="app.js"></script>

angularJS $http.get communicating with API

I am new to AngularJS and I am trying to understand it by studying sample codes.
Here I have one about $http.get, from the following link:
http://www.w3schools.com/angular/tryit.asp?filename=try_ng_customers_json
I just replaced url with one of my own but it did not work, and I am really confused, please help, thanks!
=========================
second edit: thanks to the answers, double ng-app is a mistake, but it is not the main reason for this problem. I think it has something to do with cross-site blocking, but I have turn it off on my API (I use codeigniter REST API and I set $config['csrf_protection'] = FALSE; ), I am not sure how to configure it.
<!DOCTYPE html>
<html>
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="customersCtrl">
<ul>
{{names}}
</ul>
</div>
<div ng-controller="myCtrl">
<ul>
{{names}}
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.w3schools.com/website/Customers_JSON.php")
.success(function (response) {$scope.names = response;});
});
app.controller('myCtrl', function($scope, $http) {
$http.get("https://manage.pineconetassel.com/index.php/api/v1/colors2.php")
.success(function (response) {$scope.names = response;});
});
</script>
</body>
</html>
The problem is that you have two "myApp" declarations.
From AngularJS documentation:
Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application.
So, you should move the ng-app="myApp" to the body element.
However, once you've done that you probably still won't see any result because you are cross-site scripting and browsers will (by default) block the second request.
Two ng-app directive on single page will execute the first one, 2nd one will get ignored.
Remove ng-app="myApp" from both div of your html and use angular.bootstrap to bootstrap angular app on html page using below code.
Code
angular.element(document).ready(function() {
angular.bootstrap(document, ['myApp']);
});

Failed to instantiate module myApp due to: Error: [$injector:nomod] http://errors.angularjs.org/1.2.26/$injector/nomod?p0=myApp

I'm trying to learn Angular and attempting to write my first controller outside of a web-based tutorial. I keep getting the error in the title in the JS console and can't figure out what's going on. The link takes me to a page referencing the need to include ngRoute, which I've done according to the API. Surely I'm missing something but I can't see what it is. Any help would be greatly appreciated, thanks!
index.html
<DOCTYPE html>
<html ng-app="myApp">
<head>
<title>First Angular Project</title>
<link href="bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container" ng-controller="FirstController">
Did the controller load?
</div>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="angular-route.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
app.js
(function () {
var app = angular.module('myApp', ['ngRoute']);
app.controller('FirstController', function(){
console.log("FirstController loaded");
});
})
Your issue is that you forgot to invoke the iife which registers module and controller.
(function () {
var app = angular.module('myApp', ['ngRoute']);
app.controller('FirstController', function(){
console.log("FirstController loaded");
});
})();//<-- here
Link (in the error) talks about ngRoute as a hint only for one of the reasons your module might not have been available/instantiated when angular ng-app directive tried to bootstrap it. But in your case it does not even exists due to your failure to invoke the anonymous function as IIFE.

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");
};
});

Angular.js: Uncaught error, no module: myapp

I'm trying too bootstrap an angular.js project. This is my index.html:
<!doctype html>
<html ng-app="myapp">
<head>
<meta charset="utf-8">
<base href="{% url 'app' %}" />
<title>Project</title>
</head>
<body>
<div ng-view>
<p>Loading...</p>
</div>
<script>
var url = function(path) { return '{{ STATIC_URL }}' + path };
</script>
<script src="{{ STATIC_URL }}js/jquery-1.10.1.js"></script>
<script src="{{ STATIC_URL }}js/angular.js"></script>
<script src="{{ STATIC_URL }}js/project/app.js"></script>
<script src="{{ STATIC_URL }}js/project/controllers.js"></script>
</body>
</html>
The url 'app' on the head simply prints the subpath, /app, for example. This is my app.js:
'use strict';
var app = angular.module('myapp', []);
app.config(['$routeProvider', function($router) {
$router.when('/', {
templateUrl: url('partials/foo.html'),
controller: controllers.Foo
});
}]);
The problem is that everytime I try to run it, an exception is raised: Uncaught Error: No module: myapp, and this is almost the same way angular-seed works. I searched on Google and StackOverflow but none of the answers (one and two) helped me.
Here's a fiddle about my error (you should open the browser's console to see it). What's going wrong?
The order of your script is very important, try putting it in your <head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script>
var app = angular.module('myapp', []);
app.controller('Ctrl', function($scope){
$scope.variable = "Hello";
});
</script>
<body ng-app="myapp">
<div ng-controller="Ctrl">
<p>{{variable}}</p>
</div>
</body>
Try it here:
http://jsfiddle.net/vvfnN/2/
Complementing AlexCheuk's answer, I realized that my app.js file was involved in a closure:
(function($) {
'use strict';
// all angular.js stuff
)(jQuery);
Removing the closure it worked (without changing the orders as Alex said)! I don't know exacly why, but that's ok.
I face the same problem but none of the above trick worked for me but this one, see the setting in image
Change from "OnLoad" to "No wrap - "
In my case when using IIFE notation I forgot self invoke parentheses.
(function () {
angular.module("adminApp", []);
}() //don't forget self invoke parentheses
);
i was facing the same error but i was doing a silly mistake, i was not including the controller.js file in my jsp page.
just included this:
<script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/controller.js"></script>
and it worked excellently.
I ran into a similar issue where there, while running Yeoman/grunt server.
What fixed it for me, was restarting the grunt server.

Categories

Resources