Controller
Takes the controll of a section in the HTML
- The directive is ng-controller
- AngularJS invoke the controller
- Controller use $scope as parameter
- Attach the model to $scope
$http Service
- Encapsulate HTTP communication
- GET
- POST
- PUT
- DELETE
- Can be added in any controller
$scope.user = $http.get("user/123").
}
- $http works base on PROMISE of fetch some data, therefore the code should be
var MyController = function( $scope, $http ){
$scope.user = $http.get("user/123").then (
function( response ){
$scope.message = response.data;
}
);
}
OR
var MyController = function( $scope, $http ){
var onRequestComplete = function (response) {
$scope.message = response.data;
}
$scope.user = $http.get("user/123").then( onRequestComplete );
}
Register a Controller
var app = angular.module('app', [ 'ngRoute' ]);
app.controller("MyController ", MyController );
Handle errors
- THEN function can receive as second parameter a function to handle the errors
var MyController = function( $scope, $http ){
var onRequestComplete = function (response) {
$scope.message = response.data;
}
var onError = function( reason ){
$scope.error = "Could not fetch any information";
}
$scope.user = $http.get("user/123").then( onRequestComplete, onError );
}
In the View you can display the erros as
{{ error }}
{{ error }}
Comentarios
Publicar un comentario