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!
Related
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
I have a third-party component that using jQuery (FineUploader). When a document gets uploaded, it fires an event in javascript/jquery and I need to, at that point, call a function that is inside my Angular component from the jquery code that is outside my Angular component.
The angular button works as expected but I can't get the jQuery button to call the function successfully.
Here's my plunker example code
HTML Page
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.5.8" data-semver="1.5.8" src="https://code.angularjs.org/1.5.8/angular.js"></script>
<script data-require="jquery#1.11.3" data-semver="1.11.3" src="https://code.jquery.com/jquery-1.11.3.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<script>
function widgetController() {
var model = this;
model.addWidget = function(text) {
alert(text);
}
}
var app = angular.module("app", []);
app.component("widget", {
templateUrl: "template.html",
controllerAs: "model",
controller: [widgetController]
});
</script>
</head>
<body>
<div ng-app="app">
<widget></widget>
</div>
</body>
</html>
Template Page
<center>
<p>The jQuery button below is a representing a third-party component that can't be altered and uses jquery events.</p>
<button id="addAngular" ng-click='model.addWidget("ANGULAR WORKED!!")'>Add widget using Angular</button>
<button id="addJquery">Add widget using jQuery</button>
</center>
<script>
$(function() {
//This is mocking up an event from the third-party component.
$("#addJquery").on("click", function(){
model.addWidget("JQUERY WORKED!!"); //I need to be able to call the Angular function from jQuery
});
});
</script>
I think this may have done the trick but I'm not sure if there is a better answer. Please post an alternate solution if there is a better one.
Here's the working Plunker
HTML Page
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.5.8" data-semver="1.5.8" src="https://code.angularjs.org/1.5.8/angular.js"></script>
<script data-require="jquery#1.11.3" data-semver="1.11.3" src="https://code.jquery.com/jquery-1.11.3.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<script>
var externalWidget;
function widgetController($scope, WidgetFactory) {
var model = this;
model.factory = WidgetFactory;
model.addWidget = function(text, isUpdatedExternally) {
model.isUpdated = text;
var newWidget = text;
model.factory.widgets.push(newWidget);
if(isUpdatedExternally)
{
$scope.$apply();
}
console.log("updated!");
}
model.checkWidget = function() {
console.log(model.isUpdated);
}
model.isUpdated = "NOT UPDATED";
model.addWidget("Controller initialized Widget");
externalWidget = model;
console.log(externalWidget);
}
var app = angular.module("app", []);
app.factory('WidgetFactory', function () {
var widgetList = [];
var initialWidget = "Factory Initialized Widget";
widgetList.push(initialWidget);
return {
widgets: widgetList
};
});
app.component("widget", {
templateUrl: "template.html",
controllerAs: "model",
controller: ["$scope", "WidgetFactory", widgetController]
});
</script>
</head>
<body>
<div ng-app="app" id="ngApp">
<widget></widget>
<br />
<center><button id="addJquery">Add widget using jQuery</button></center>
</div>
<script>
$(function() {
//This is mocking up an event from the third-party component.
$("#addJquery").on("click", function(){
externalWidget.addWidget("JQUERY WORKED!!!", true);
});
});
</script>
</body>
</html>
Template Page
<center>
<p>The jQuery button below is a representing a third-party component that can't be altered and uses jquery events.</p>
<button id="addAngular" ng-click='model.addWidget("ANGULAR WORKED!!")'>Add widget using Angular</button>
<button id="checkAngular" ng-click='model.checkWidget()'>Check widget using Angular</button>
</center>
<ul>
<li ng-repeat="w in model.factory.widgets">
{{w}}
</li>
</ul>
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
pls, help me with next question
I try to implement conditional classes on div blocks using ng-class but have encountered next problem - "it is not working". Example seems to be very simple, I even do not know how else it can be described.
But one more idea - controller does not working instead of ng-class.....i do not know.
Here you can see my code pls, probably you will find smth wrong or give me an advice.
http://plnkr.co/edit/Zm0g4QfkqzTD3h4FWfcp?p=preview
demoApp = angular.module('demoApp',[]);
var controllers = {};
controllers.testCntr = function ($scope)
{
$scope.setClass = function()
{
alert('works');
return True;
}
};
HTML
<!doctype html>
<html ng-app="demoApp">
<head>
<title></title>
<style>
.red
{
color:red;
}
</style>
<script src="angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-route.js"></script>
</head>
<body>
<div ng-controller="testCntr">
<span ng-class="{red: $scope.setClass()}">Test color</span>
<div>{{$scope.setClass()}}</div>
</div>
</body>
</html>
Thanks for your amendments.
Several problems here.
You can only add one controller at a time with .controller()
In your template, $scope is already the context, so don't include it in the HTML
True should be true
You are missing an ng-app directive
angular.js is not included properly
Your scripts.js is not included
Here's a working version of your Plunkr with the changes above: http://plnkr.co/edit/ybDScjDrrIkH8tBNfIg1?p=preview
When you call a function which is in the scope from the view, just call it like that :
<body ng-app="app">
<div ng-controller="Ctrl">
<span ng-class="{'red': setClass()}">Test color</span>
<div>{{setClass()}}</div>
</div>
</body>
Here the Working Plunkr
You should create an app.js services.js and controllers.js
Your controller should be moved to the controllers.js and look a little something like this.
demoApp.controller('testCntr',function ($scope){
$scope.setClass = (function(){
alert('works');
return True;
})
});
To add the controller to your app you should do this
demoApp.controller('testCntr', function ($scope) {
$scope.setClass = function() {
alert('works');
return True;
}
})
Working Plunkr: http://plnkr.co/edit/LPY94jPJdIJX4pr9K5FY?p=preview
Working Demo:
demoApp = angular.module('demoApp',[]);
demoApp.controller('testCntr', function ($scope) {
$scope.setClass = function() {
alert('works');
return 33;
return True;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" <div="" ng-controller="testCntr">
<span ng-class="{red: $scope.setClass()}">Test color</span>
<div>{{setClass()}}</div>
</div>
your script.js file should be
var app = angular.module('demoApp',[]);
app.controller('testCntr', ['$scope', function($scope) {
$scope.setClass = function() {
return true;
};
}
]);
and html:
<!DOCTYPE html>
<html ng-app="demoApp">
<head>
<script src="angular.min.js"></script>
<script src="script.js"></script>
<style>
.red {
color:red;
}
</style>
</head>
<body ng-controller="testCntr">
<span ng-class="{red: setClass()}">Test color</span>
</body>
</html>
It may solve your problem
Plunker link: http://plnkr.co/edit/Ftx3M0aG9G8cJtyrn5wj?p=preview
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";
}])