JOHN Mickh
JOHN Mickh

Reputation: 35

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

Upvotes: 2

Views: 5068

Answers (2)

Romain Le Qllc
Romain Le Qllc

Reputation: 896

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

Upvotes: 0

mwilson
mwilson

Reputation: 12900

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

Upvotes: 1

Related Questions