Nathan Martins Nathan Martins - 1 year ago 69
AngularJS Question

Using $http as a function parameter - AgularJS

Iḿ trying to use this angular material chip.
(CONTACT CHIP - With auto-complete)
https://material.angularjs.org/latest/demo/chips

And it has a different structure of what Iḿ used to. I want to adapt to get the contacts from my mongodb with $http, like:

$http.get("/contacts").success(function(response) {
contacts = response;
});


But in their Angular Material code example is like this:

angular.module('MyApp',['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])
.controller('ContactChipDemoCtrl', DemoCtrl);
function DemoCtrl ($q, $timeout) {
...
function loadContacts() {
var contacts = [
'Marina Augustine',
'Oddr Sarno',
'Nick Giannopoulos',
'Narayana Garner',
'Anita Gros',
'Megan Smith',
'Tsvetko Metzger',
'Hector Simek',
'Some-guy withalongalastaname'
];
}
...


How can I use $http as a parameter for the DemoCtrl function? To get the contacts from db

Answer Source

You are assigning response data to variable contacts which has no angular scope context

If you are using $scope as your data model for view it would be

$http.get("/contacts").then(function(response) {
          $scope.contacts = response.data;
});

Or if using controllerAs alias in view:

var vm = this
$http.get("/contacts").then(function(response) {
          vm.contacts = response.data;
});

Also need to inject $http in controller