简体   繁体   中英

How can I use javascript code inside angularjs?

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 :-

  1. It will add dependency injection proprely which is a basic concept behind angularjs

  2. It will ensure that the external function exist before starting app.

  3. It will add more flexibility and control over the java script function in angular.

  4. The below snippet will remove the external access of function and secure your application
  5. 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!

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