javascript 对于在 angularjs 控制器中定义的函数,函数未定义错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17561883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:47:07  来源:igfitidea点击:

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

javascriptangularjsangularjs-controller

提问by Steven

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.

我查看了其他“函数未定义”问题,但似乎无法找到适用于我的用例的问题。我正在使用 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 onChangeevent of a checkbox.

我有一个最初为空的 div #mylist,我正在 js 中动态填充它。我在控制器中定义了一个函数,我将其分配给onChange复选框的事件。

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.

我在这里错过了什么?谢谢。

采纳答案by shaunhusain

<!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/

http://jsfiddle.net/y6XhY/

回答by Hazarapet Tunanyan

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 onChangeyou can use ngChangedirective (only you have to set ngModel on that input).

如果您使用 AngularJs,最好在控制器范围内定义函数。$scope 的字段可以是您的函数,您可以使用ngChange指令代替onChange(只有您必须在该输入上设置 ngModel)。

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