简体   繁体   中英

Function not defined error for a function that's defined inside an angularjs controller

I've looked through other "function is not defined" questions, but can't seem to find one that's applicable to my use case. I'm using angular.js.

I have an initially empty div, #mylist that I am populating dynamically in the js. I have a function defined inside a controller that I'm assigning to onChange event of a checkbox.

Here is the full doc:

<!doctype html>
<html data-ng-app="testapp">
<head>
    <script src="jquery-1.10.2.min.js"></script>
    <script src="angular.min.js"></script>
    <script>
        var app = angular.module("testapp", []);        
        app.controller("MyAppController", function ($scope) {
            createCheckbox();

            function doSomething() {
                alert("hello!");
            }

            function createCheckbox() {
                $("#mylist").html("<input type='checkbox' onChange='javascript:doSomething();' />");
            }       
        });
    </script>
</head>

<body data-ng-controller="MyAppController">
    <div id="mylist"></div>
</body>
</html>

When run, clicking on the checkbox results in the function not defined error.

What am I missing here? Thanks.

<!doctype html>
<html data-ng-app="testapp">
<head>
    <script src="jquery-1.10.2.min.js"></script>
    <script src="angular.min.js"></script>
    <script>

var app = angular.module("testapp", []);

app.controller("MyAppController", function ($scope) {
    $scope.someProperty = true;


    $scope.$watch("someProperty", function (someProperty){
       alert("hello!"+someProperty)
     });
});

    </script>
</head>
<body data-ng-controller="MyAppController">
    <div id="mylist"><input type="checkbox" ng-model="someProperty"/></div>
</body>

</body>
</html>

http://jsfiddle.net/y6XhY/

If you use AngularJs, it's good practice to defined function inside you controller scope.$scope's field can be your function and instead of onChange you can use ngChange directive (only you have to set ngModel on that input).

$scope.doSomething = function() {
    alert("hello!");
}

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