Sai_23
Sai_23

Reputation: 427

Error in calling javascript from angularjs

I am new to angularJS.Can i call my javascript function from angularJS ?

let say my javascript file is as follows containing a function :

test.js

function showAlert() {
 alert('something');
}

and my angular code is:

Script.load("test.js");
$scope.sampleFunction = function() {
                showAlert();
              };

currently it is not working properly. Suggestions please.

Upvotes: 0

Views: 731

Answers (2)

Vaibhav Jain
Vaibhav Jain

Reputation: 3755

I created an example in which i called angularJS controller and from controller calling another java script function.

Follow These Steps:

(1) Create a folder Test.

(2) Save angular.min.js from the link http://code.angularjs.org/1.2.0rc1/angular.min.js.

(3) Create a file1.js Page in the same folder :

file1.js

function alertNumber(number) {
alert(number);
}

(4) Create file2.js Page in the same folder :

file2.js

var app = angular.module('demo',[]);

function alertOne() {
 alertNumber("one");
}

(5) Create index.html Page in the same folder :

index.html

<html ng-app="demo">
<head>
<script src="angular.min.js"></script>
<script src="file1.js" type="text/javascript"></script> 
<script src="file2.js" type="text/javascript"></script> 

</head>
<body>

  <div ng-controller="alertOne">

</body>
</html>

(6) Run the index.html Page.

Description: It will call the controller alertOne and alertOne will call the javascript function alertNumber with an argument.

Upvotes: 1

Tzu ng
Tzu ng

Reputation: 9244

You can do something like this :

test.js 

window.showAlert = function() {//code};


angularjs_code.js

$scope.sampleFunction = function() { window.showAlert(); }

But still, I strongly suggest you to transfer your old to work in angular way [ into controller, directive ... ] if you really want to learn angularJS

Upvotes: 1

Related Questions