简体   繁体   中英

Having a formular call a controller in AngularJS

I'm having a little issue with learning AngularJS. I'm not 100% sure what are controller about. For exemple, i have the following html div which simply display the result of a SQL request :

<div ng-app="searchApp" ng-controller="searchCtrl"> 
<table>
        <tr ng-repeat="x in names"> 
        <td>{{ x }}</td> 
        </tr>
    </table>
</div>

And here's the controller :

<script>
var app = angular.module('searchApp', []);
app.controller('searchCtrl', function($scope, $http) 
{   
    $http.get("server.php")
    .then(function (response) 
    {
        $scope.result = response.data;
    })
    .then(function(response){
        console.log(response);
    })
});
</script>

server.php is returning a simple array of strings, so the page display immediatly a list of names. I would like to add a button on this page, and display this list only AFTER the button has been clicked. I tried to add a form :

<div ng-app="searchApp" ng-controller="searchCtrl"> 
<form class="well form-search">
    <button type="submit" class="btn" ng-click="search()">Search</button>
</form>
    <table>
        <tr ng-repeat="x in result"> 
        <td>{{ x }}</td> 
        </tr>
    </table>
</div>

but this form is calling the search() function, which doesn't exist right now. I would like to call the controller instead.

I don't know if i have made myself very clear, sorry.

//template (no form tag needed)
<button type="button" class="btn" ng-click="search()">Search</button>

//controller
$scope.search = function(){
 $http.get("server.php")
    .then(function (response) 
    {
        $scope.result = response.data;
    })
    .then(function(response){
        console.log(response);
    })
}

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