Reputation: 1098
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.
Upvotes: 3
Views: 10937
Reputation: 2865
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!");
}
Upvotes: 0
Reputation: 19748
<!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>
Upvotes: 1