Angular: Controller as syntax when calling the $http service

Plnkr.co:

http://plnkr.co/edit/USnzVuVm9pC0Jg7hMXCm?p=preview

Plnkr01 Plnkr02

So that all works as expected… but I don’t seem able to use the Controller As syntax. Maybe that is right? Another day.

(Another day…)

Thanks Ignacio. So this is how you have to expose [this], or at least a way to do it:

Plnkr03

So digest the [var me = this;] piece, allowing other properties to be exposed. Then in the calling html, we can go back to our preferred [Controller as] syntax:

Plnkr04

And a sample of the output:

Plnkr05

Final go – this time the controller in index.html is a child of the app myViewer, and inside script.js it’s all in an IIFE:

Plnkr06

Plnkr07

(function() {

var app = angular.module(“myViewer”,[]);

var MainCtrl = function($http) {

var me = this;

var onUserComplete = function(response) {
me.user = response.data;
};
$http.get(“https://api.github.com/users/angular”)
.then(onUserComplete);

me.message= “GitHub Viewer”;

};

app.controller(“MainCtrl”, [“$http”, MainCtrl]);

}());

<!DOCTYPE html>
<html ng-app=”myViewer”>

<head>
<link rel=”stylesheet” href=”style.css”>
<script src=”https://code.angularjs.org/1.3.0-beta.3/angular.js”></script&gt;
<script src=”script.js”></script>
</head>

<body ng-controller=”MainCtrl as stuff”>
<h1>{{stuff.message}}</h1>

Name: {{stuff.user.name}}

<div>
Name: {{stuff.user.type}}
</div>
<img ng-src=”{{stuff.user.avatar_url}}” title=”{{stuff.user.name}}”>
</body>

</html>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s