简体   繁体   中英

How to call a AngularJS controller using onclick event

This is my code in javascript.

    function Hello($scope, $http) {
    $http.get('<c:url value='/learningresources/ajaxvalue'/>').
    success(function(data) {
        $scope.response = data;
    });
 }

This code gets a list of records from spring controller. I want this same to return the result bu onclick event. How can i do that?

You can create a function for ng-click like:-

HTML:-

<button ng-click="clickme()">Click me</button>

Controller:-

$scope.clickme=function(){
   $http.get('<c:url value='/learningresources/ajaxvalue'/>').
     success(function(data) {
       $scope.response = data;
    });

}

javaScript

var myApp = angular.module('myApp',[]);
myApp.controller('yourCtrl', ['$scope', '$http', function($scope, $http) {
    $scope.clickFun = function(){
        $http.get('<c:url value='/learningresources/ajaxvalue'/>').
            success(function(data) {
                $scope.response = data;
        });
    }
}]);

HTML

<div ng-controller="yourCtrl">
    <button ng-click="clickFun()">Your btn</button>
</div>

This works!

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