简体   繁体   中英

http get response in scope with ng-view

I'm writing a controller in AngularJS that calls http.get to an API, and returns a 0 (for now). I managed to display 0 on the console without problems, but I can not display it in the $scope on the front.

App.js

.controller('ssnGenAltaCtrl', ['$scope', '$http',
    function($scope, $http){
        $scope.generarRubricaAlta = function(data){
        $http({
            method: 'GET',
            url: 'url'
            }).then(function successCallback(data) {
                console.log(data.data);
                $scope.mensaje = data.data;
            }, function errorCallback(data) {
                console.log("Error");
            });
        }
    }]);

HTML

<div>
    <a class="btn btn-default" href="#" role="button" ng-click="generarRubricaAlta()">Generar Rubrica Alta</a>
    <p class="bg-primary">{{mensaje}}</p>
</div>

Routing

.when("/ssnGenAlta", {
    templateUrl : "views/ssnGenAlta.html",
    controller: "ssnGenAltaCtrl"
})

JSON Output

Object
config: Object
data: "0"
headers: (d)
status: 200
statusText: "OK"
__proto__: Object

Thanks!

The issue is in the anchor tag:

The href attribute redirects to #

<div>
    <a class="btn btn-default" x:ng:href="javascript:void(0)" role="button" ng-click="generarRubricaAlta()">Generar Rubrica Alta</a>
    <p class="bg-primary">{{mensaje}}</p>
</div>

Replace it with x:ng:href="javascript:void(0)"

Also initialize $scope.mensaje = "123"; before method declaration

Check if two way binding works or not. If it does, change back to $scope.mensaje = "";

.controller('ssnGenAltaCtrl', ['$scope', '$http',
function($scope, $http){
    $scope.mensaje = "123"; //change this back to empty string
    $scope.generarRubricaAlta = function(data){
    $http({
        method: 'GET',
        url: 'url'
        }).then(function successCallback(data) {
            console.log(data.data);
            $scope.mensaje = data.data;
        }, function errorCallback(data) {
            console.log("Error");
        });
    }
}]);

code was current, I think you just need to define variable before API calling

.controller('ssnGenAltaCtrl', ['$scope', '$http',
function($scope, $http){
$scope.mensaje = {};//you need to define variable before API calling for 2way data binding. 
    $scope.generarRubricaAlta = function(data){
    $http({
        method: 'GET',
        url: 'url'
        }).then(function successCallback(data) {
            console.log(data.data);
            $scope.mensaje = data.data;
        }, function errorCallback(data) {
            console.log("Error");
        });
    }
}]);

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