I have just started working on Angularjs and facing a problem in calling the factory defined in other module. Actually I need to clean the code so I have to build all the functionalities in one js file and I have to use them in my main js file where I have defined my controllers. I have made a simple code to understand the problem. Thanks in advance
Following is the Html file:-
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.1.5" data-semver="1.1.5" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="function.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="MyServiceModuleOne">
<div ng-controller="TestController">
<button type="button" ng-click="getFn()"> Test </button>
</div>
</body>
</html>
Following is script.js file
var myModule= angular.module('MyServiceModuleTwo',['MyServiceModuleOne']);
myModule.controller('TestController', ['$scope', 'notify', function($scope, notify){
$scope.getFn = function() {
notify.sampleFun();
}
}]);
Following is function.js file:-
var myModule = angular.module('MyServiceModuleOne', []);
myModule.factory('notify', function() {
return {
sampleFun: function() {
alert('hi');
}
};
});
There are couple of changes needed.
You are referencing MyServiceModuleOne as root module, but the controller you are referencing is in MyServiceModuleTwo.
So change your ng-app from MyServiceModuleOne to MyServiceModuleTwo.
I've updated the plnkr
Related
I need to run this code in angularjs.
When I try to execute this model function it is not running.
It is not even showing alert or console.
So what is the way to use this script files in angularjs
Here is my code in example.html:
<div>
{{sample}}
</div>
<div><button ng-click="name()"></div>
<script>
function name(){
alert("text");
}
</script>
If i understand your requirement correctly,
You need to execute a separate java-script function.
For an angular application it is not a proper way to run javascript out of scope of angular.
any if it is absolutely requried you can try replacing ng-click="name()" with onclick="name()"
var app = angular.module("app", []);
app.controller('exampleController', [function() {
this.myFunction = function() {
alert("Iam from angular controller");
}
}]);
function myFunction() {
alert("Iam from javascript");
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="app" ng-controller="exampleController as ctrl">
<button ng-click="ctrl.myFunction()">click me</button>
<button onclick="myFunction()">click me</button>
</div>
#Update
If you want to use a java script library or function or constants in angularjs the my suggested way is to add a factory or service that ensure the library or function or constants but it is not simple as above solution.Here iam adding a snippet based on above solution
There are some advantages of using following approch :-
It will add dependency injection proprely which is a basic concept behind angularjs
It will ensure that the external function exist before starting app.
It will add more flexibility and control over the java script function in angular.
The below snippet will remove the external access of function and secure your application
This is the best way in which you can add external libraries like jquery loadash or any js libraries to your code
(function() {
function exampleController(myFunction) {
this.myFunction = function() {
alert("Iam from angular controller");
}
this.externalJSFunction = myFunction
};
exampleController.$inject = ['myFunction'];
function myFunctionFactory($window) {
if (!$window.myFunction) {
throw new Error("myFunction is not defined");
}
this.myFunction = $window.myFunction;
/* You can add
$window.myFunction = undefined;
if the function ($window.myFunction) is not required by
some other library or function in window scope
in such cases it gives added security by
restricting access of this from window scope and dis allows modification
*/
return this.myFunction;
}
myFunctionFactory.$inject = ['$window'];
var app = angular.module("app", []);
app.controller('exampleController', exampleController);
app.factory('myFunction', myFunctionFactory);
})();
function myFunction() {
alert("Iam from javascript");
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="app" ng-controller="exampleController as ctrl">
<button ng-click="ctrl.myFunction()">click me For angular Function</button>
<br/>
<button ng-click="ctrl.externalJSFunction()">click me For external JS Function </button>
<br/>
<button onclick="myFunction()">click me for checking exteranl acess </button>
</div>
your code should be like this....
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script >
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name=function(){
alert("text");
}
});
</script>
</head>
<body ng-controller="MainCtrl">
<div>
{{sample}}
</div>
<div><button ng-click="name()">click me</div>
</body>
</html>
You need to give angular js cdn first and then a create a module and controller like above
Here is a sample controller.
<body ng-app="myApp" ng-controller="myCtrl">
<div>
<button ng-click="name()">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = name;
function name(){
alert("text");
}
});
</script>
</body>
You could use a directive, here is an example:
// in your JS source
angular.directive('something', [function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('click', function() {
alert('yup');
});
}
};
}]);
// in your HTML file
<button type="button" something>Click Me!</button>
This allows you to reuse your various code chunks / functions across your entire project pretty easily.
Another Solution
<!DOCTYPE html>
<html>
<head>
<title>example</title>
<script data-require="jquery#*" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body ng-app="app" ng-controller="exampleController as ctrl">
<button ng-click="ctrl.name()">click me to angular</button>
<button ng-click="name()" class="btn">click me to javascript</button>
<script>
var app = angular.module("app", []);
app.controller('exampleController', [function() {
this.name = function() {
alert("angular text");
}
}]);
//JQuery Lib must be included your project
$(document).on('click', '.btn', function() {
eval($(this).attr('ng-click'));
});
function name() {
alert("javascript text");
}
</script>
</body>
</html>
You should be able to run any javascript inside of an angular controller inside of a script tag in an html file.
Your html file should look something more like this:
<!DOCTYPE html>
<html>
<head>
<title>example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body ng-app="app" ng-controller="exampleController as ctrl">
<button ng-click="ctrl.name()">click me</button>
</body>
</html>
<script>
var app = angular.module("app", []);
app.controller('exampleController', [function() {
this.name = function(){
alert("text");
}
}]);
</script>
Create a service layer and glue it inside the controller. Now, you can reuse the created function in multiple controllers.
For implementation,
How can I call javascript function in AngularJS controller?
I hope this helps!
I have a very basic example that isn't working: I have two aspects, the index.html and the main.js. They are in the same folder:
<!DOCTYPE html>
<html>
<head>
<title> AngularJS Tutorials </title>
<link rel="stylesheet" href="css/foundation.min.css">
<script src="main.js"></script>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
<h1>{{data.message}}</h1>
</div>
</div>
<script type="text/javascript" src="js/angular.min.js"></script>
</body>
</html>
main.js
function FirstCtrl($scope) {
$scope.data = {message: "Hello"};
}
my page shows this:
{{data.message}}
You need to add the controller to the angular module. you can use the controller function to add the js function for your controller.
var FirstCtrl = function FirstCtrl($scope) {
$scope.data = {message: "Hello2"};
};
angular.module("myApp",[]).controller("FirstCtrl",FirstCtrl);
If you already had the angular module defined somewhere else in the page, Use this version.
angular.module("myApp").controller("FirstCtrl",FirstCtrl);
Here is a working sample http://jsbin.com/tiroteharu/edit?html,js,console,output
<script src="~/Scripts/angular/angular.js"></script>
<script>
var myApp = angular.module('myApp', []);
myApp.controller('FirstCtrl', ['$scope', function ($scope) {
$scope.data = { message: "Hello" };
}]);
</script>
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
<h1>{{data.message}}</h1>
</div>
</div>
More help read: https://docs.angularjs.org/guide/controller
I'm new to Angular JS.
I have a few questions. Scope seems to be working with my first controller testController but not with my second controller controlspicy.
Why is not letting me print out $scope.greeting ? Shouldn't the binding work because I assigned a controller.
Here's a plunkr link which directs straight to the code.
http://plnkr.co/edit/NbED8vXNiZCqBjobrISa?p=preview
<!DOCTYPE html>
<html ng-app="newtest">
<head>
<script data-require="angular.js#*" data-semver="1.3.5" src="https://code.angularjs.org/1.3.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<script src="spicy.js"></script>
</head>
<body ng-controller="testController">
<h1>Hello Plunker! {{message}}</h1>
<input type="text" name="firstName" ng-model="thetext">
{{double(thetext)}}
<h1 ng-controller="controlspicy">new test</h1>
<h2>{{greeting}}</h2>
</body>
</html>
script.js
var app = angular.module("newtest", [])
.controller("testController", ["$scope", function($scope) {
$scope.message = "hola";
$scope.double = function(value){
if (value == null){
return 0;
}
return value*2;
};
}]);
spicy.js
var appl = angular.module("thespicy", [])
.controller("controlspicy", ["$scope", function($scope){
$scope.greeting = "hello";
}]);
As previously mentioned by Preston you need to wrap the <h2> inside a tag with ng-controller. There is one more issue however.
controlspicy is defined in another module than the one you specify in ng-app.
Change angular.module("thespicy", []) in spicy.js to angular.module("newtest").
You should almost never use more than one module in one app. You could however divide it into different sub-modules but if your new to Angular I would recommend using just one module to start with.
To clarify; you should only define a module once by typing angular.module("module_name", []). Notice the [] here. In this array you would put dependencies for the module (if you really wanted the 'thespicy' module you could have included it as a dependency with angular.module("newtest", ['thespicy']). If you later wanted to add a controller to the module you would reference the module with angular.module("module_name") (no []). For example:
// Define a module
angular.module('foo', []);
// Reference the previously defined module 'foo'
angular.module('foo')
.controller('barCtrl', function() { ... });
Here is a working fork of your example: http://plnkr.co/edit/rtUJGeD52ZoatoL3JgwY?p=preview btw.
The nested controller only controls inside the scope of the tag. In this case, it only has access to the scope inside of the h1 tag.
Try this:
<!DOCTYPE html>
<html ng-app="newtest">
<head>
<script data-require="angular.js#*" data-semver="1.3.5" src="https://code.angularjs.org/1.3.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<script src="spicy.js"></script>
</head>
<body ng-controller="testController">
<h1>Hello Plunker! {{message}}</h1>
<input type="text" name="firstName" ng-model="thetext">
{{double(thetext)}}
<div ng-controller="controlspicy">
<h1>new test</h1>
<h2>{{greeting}}</h2>
</div>
</body>
</html>
Here's a working plunker of your example: http://plnkr.co/edit/gufbBI4i68MGu8FWVfJv?p=preview
I should point out that you didn't include your controller in your main app.
script.js should start like this:
var app = angular.module("newtest", ['thespicy'])
You have multiple apps
check this plunkr for working nested controllers
<div>
<div ng-controller="testController">
<h1>Hello Plunker! {{message}}</h1>
<input type="text" name="firstName" ng-model="thetext">
{{double(thetext)}}
</div>
<div ng-controller="thespicy">new test
<h2>{{greeting}}</h2>
</div>
</div>
script.js
var app = angular.module("newtest", [])
.controller("testController", ["$scope", function($scope) {
$scope.message = "hola";
$scope.double = function(value){
if (value == null){
return 0;
}
return value*2;
};
}])
.controller('thespicy', ["$scope", function($scope) {
$scope.greeting = "Hello";
}])
I couldn't get my angular code to run in plunker. I have attached the details. Could any of you help me out? Basically it's a problem with ngcontroller I guess but I am not sure.
<!DOCTYPE html>
<html ng-app>
<head>
<script data-require="angular.js#*" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
{{ 5 / 2 }}<br>
{{message}}
</body>
</html>
Contents of javascript script.js file
var MainController = function($scope){
$scope.message = "Welcome!";
};
Plunk
http://plnkr.co/edit/mzgdELALCP7DN2ikJHsC?p=preview
In version 1.3.*, you cannot longer declare a global controller function.
Instead define a module, and use your controller function:
var SidController = function($scope){
$scope.message = "WElcome.";
};
SidController.$inject = ['$scope'];
angular.module('app', []).controller('SidController', SidController);
In your html
<html ng-app="app">
See this plunker.
I had the same issue.. Well done on starting a tutorial! Simply replace the script in your index.html with
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
I suppose the library Plunker currently has is outdated or something.
Working Plunkr (with a different AngularJS version. #user3906922 has a better answer, where your version stays the same).
Use this for HTML for instance:
<!doctype html>
<html ng-app>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="SidController">
<h1>Hello Plunker!</h1>
{{ 5 / 2 }}<br>
{{message}}
</div>
</body>
</html>
Check this plunkr
You need to define your module and then register the controller
http://plnkr.co/edit/9zAV5nSWH05FYscEWYZ5?p=preview
angular.module( 'demoApp', []);
angular.module( 'demoApp' )
.controller( 'SidController', function($scope){
$scope.message = "WElcome.";
});
You should create your module.
angular.module('app', []).controller("SidController", function($scope) {
$scope.message = "WElcome.";
});
Then in your html element, set your attribute like this:
ng-app="app"
I included angular js in my asp.net mvc project but when i call object in controller
the angular js expressions do not evaluate
here is the app.js code please suggest
var app = angular.module('app', []);
app.controller('createController', createController);
and here is the createController code
var createController = function ($scope) {
$scope.mydata = 'I work!';
}
here is what i include in html
<html ng-app="app">
<script src="~/Scripts/angular.min.js"></script>
<script src="~/appAjs/app.js"></script>
<script src="~/appAjs/controllers/createController.js"></script>
<div ng-controller="createController">
{{scope.mydata}}
{{6+9}}
from your code, I can only suspect two things
your javascript does not have the proper scope
do not use the word scope in your "scope" code
first part: javascript scope:
Always use an IIFE, in your case your code should look like:
(function(){
var app = angular.module('app', []);
var createController = function ($scope) {
$scope.mydata = 'I work!';
};
app.controller('createController', createController);
}());
second part: don't use the word scope
in your HTML, you should not use the word scope as it's already inherit in your controller as that's the model you are passing to the "view"
hence, your code should look like:
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div ng-controller="createController">
{{mydata}}
{{6+9}}
</div>
</body>
</html>
the result is:
I work! 15
live code in JSBIN so you can check it out.
your HTML page, all together should look like this:
if you have only one file
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<title>My AngularJs App</title>
</head>
<body>
<!-- HTML -->
<div ng-controller="createController">
{{mydata}}
{{6+9}}
</div>
<!-- AngularJS required -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<!-- AngularJS code -->
<script>
(function(){
var app = angular.module('app', []);
var createController = function ($scope) {
$scope.mydata = 'I work!';
};
app.controller('createController', createController);
}());
</script>
</body>
</html>
if you're using 2 files
file index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<title>My AngularJs App</title>
</head>
<body>
<!-- HTML -->
<div ng-controller="createController">
{{mydata}}
{{6+9}}
</div>
<!-- AngularJS required -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<!-- AngularJS extra files -->
<script src="createController.js"></script>
</body>
</html>
file createController.js (in the same folder as index.html)
(function(){
var app = angular.module('app', []);
var createController = function ($scope) {
$scope.mydata = 'I work!';
};
app.controller('createController', createController);
}());
I think the problem may well be the order in which you are including your scripts:
Try the following:
<script src="~/Scripts/angular.min.js"></script>
<script src="~/appAjs/controllers/createController.js"></script>
<script src="~/appAjs/app.js"></script>
Reasoning is that app.js tries to define a controller using a function that has not been defined when the function is run.
Points that {{scope.data}} should be {{data}} are correct, but do not explain {{6+9}} not working.
You need to create the controller in the context of the app module.
Your app.js should just have
angular.module('app', []);
and your createController code should look similar to this
angular.module('app')
.controller('createController', function ($scope) {
$scope.mydata = 'I work!';
});
You need to change the expression from
{{scope.mydata}}
to
{{mydata}}
Expression have access to scope and no keyword is required to access a scope object.