简体   繁体   English

在angularjs控制器中定义的函数的函数未定义错误

[英]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. 我正在使用angular.js。

I have an initially empty div, #mylist that I am populating dynamically in the js. 我最初有一个空的div,即#mylist,我正在js中动态填充它。 I have a function defined inside a controller that I'm assigning to onChange event of a checkbox. 我在控制器中定义了一个函数,该函数分配给复选框的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. 谢谢。

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

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). 如果使用AngularJs,则最好在控制器范围内定义函数。$ scope的字段可以是您的函数,可以使用ngChange指令代替onChange (仅需在该输入上设置ngModel)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM