简体   繁体   中英

How to call Javascript function in Angularjs

Here I'm getting an error as myFunction() IS NOT DEFINED:

app.controller('myctrl',function(){
    myFunction();
});

function myFunction() {
    debugger;
    document.getElementById("abc").disabled = false;
}

Here myFunction is onclick="myFunction()" but I'm trying to call it in my function
What mistake I'm doing? please help me

You shouldn't be defining functions outside of your angular controller. When you do this, you lose the angular context since angular doesn't know it took place. You'll start seeing some wackyness such as two way data binding issues along with other things.

Secondly, you need to import the $scope module into your controller so you can define functions on it. There are other ways to do this, but this is the most common.

https://jsfiddle.net/mswilson4040/ty43egxo/

<div ng-app="myApp" ng-controller="myCtrl">
  <button ng-click="alertAgain()">
   Show an alert
  </button>
</div>



const dontdothis = () => {
    alert('function should be within the angular controller');
};
const app = angular.module('myApp', []);
app.controller('myCtrl', ($scope) => {
    dontdothis();

    $scope.alertAgain = () => {
        alert('this is an alert again');
    };
});

https://docs.angularjs.org/guide/scope

This is a scope issue.

If you want to use a function from your html, you have to link your function to the scope of your controller, byt adding $scope. to myFunction, so you get

app.controller('myctrl', ['$scope', function() {
    $scope.myFunction();
}]);

function myFunction() {
    debugger;
    document.getElementById("abc").disabled = false;
}

Moreover, if your function job is to make an element noy disabled, you can u se ng-disabled,I made a working example on Plunker using ng-disabled

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