简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM