2

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

4
  • Please share the full and exact error message Commented Jan 10, 2019 at 15:09
  • @NicoHaase Here i m calling myFunction in onclick=myFunction()" When i click on Button its Working But When i call in Function its calling but not working Commented Jan 10, 2019 at 15:12
  • 3
    Please add the full and exact error message to the question. I assume it is a problem of scoping Commented Jan 10, 2019 at 15:13
  • I also suggest you to provide a minimal reproducible example. The piece of code you've shown doesn't seem to be errorneous by itself Commented Jan 10, 2019 at 15:55

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

You need to import $scope into your function. $scope is undefined in your answer. It's correct on your plunker though.
Indeed, edited my answer so now $scope is imported. Thanks !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.