简体   繁体   中英

JS function defined in AngularJS controller not working

The following is my controller code:

app.controller('HomeController', ['$scope', '$location', '$sce', '$routeParams', '$timeout', function($scope, $location, $sce, $routeParams, $timeout ) {
    // Configuration Variables:
    $scope.title = "Site Title";
    $scope.logosrc = "images/site_logo.gif";
    $scope.tagline = "This is the new tagline!!!";

    // This changes the shadowed aspect of the top nav and footer based on a checkbox
    $scope.shadowChange = function(cb){
        alert ("hi");
        return true;
    };

    // This converts any HTML code in the text to actual code so that it renders properly
    $scope.renderHtml = function(html_code)
    {
        return $sce.trustAsHtml(html_code);
    };

}]);

I call the shadowChange function in my code using an onClick on a checkbox like so:

<input type="checkbox" name="shadow" id="shadow" checked onClick="shadowChange(this);" />

Not only do I have HomeController tied to the body tag, I also (just in case) wrapped the relevant code in ANOTHER div using HomeController, and Chrome Inspector even tells me that HomeController is loading up fine.

In addition, those configuration variables at the top of the controller are being set properly.

Yet, when I click the checkbox I get an error that shadowChange is undefined. I get the same error if I try (just for testing) the other function there, renderHtml. Yet, in another application of mine, I use it the SAME EXACT WAY and it works fine.

I cannot see what's preventing the code from seeing the functions.

Thoughts?

You want to use the ng-click directive in order to access the scope of the controller. (instead of onClick )

<input type="checkbox" name="shadow" id="shadow" checked ng-click="shadowChange(this);" />

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