【问题标题】:Using $http as a function parameter - AngularJS使用 $http 作为函数参数 - AngularJS
【发布时间】:2016-07-19 17:52:47
【问题描述】:

我正在尝试使用这个 AngularJS 材料芯片。 (联系芯片 - 具有自动完成功能) https://material.angularjs.org/latest/demo/chips

而且它的结构与我习惯的不同。我想适应使用 $http 从我的 mongodb 获取联系人,例如:

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

但在他们的 Angular Material 代码示例中是这样的:

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'
  ];
}
...

如何使用 $http 作为 DemoCtrl 函数的参数?从 db 中获取联系人

【问题讨论】:

  • 密码笔链接在哪里?
  • 你只是在问依赖注入如何与 Angular 一起工作?我建议你看看文档docs.angularjs.org/guide/di
  • @Sajeetharan 点击上面的链接并转到 CONTACT CHIP,有一个 codepen 图标

标签: javascript angularjs mongodb


【解决方案1】:
MyModule.controller("DemoController", DemoCtrl);

DemoCtrl.$inject = ['$http'];

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

以上是设置控制器的首选方式,因为它不使用匿名函数,而不是:

MyModule.controller("DemoController", ['$http', function($http) {
     $http.get("/contacts").success(function(response) {
      contacts = response;
}]);

【讨论】:

  • 我要在这里试试
  • 另外——@charlietfl 是对的——你还应该注入 $scope 并设置 $scope.contacts = response.data;
  • Onde question @Booza 在我的函数 DemoCtrl 中有一些参数 DemoCtrl($q,$timeout)。当我注入 $http 时,这现在应该是第一个参数,对吧!?
  • 无论字符串的顺序是什么,都应该是参数的顺序。只要他们匹配就没有关系。
【解决方案2】:

您正在将响应数据分配给没有角度范围上下文的变量 contacts

如果你使用 $scope 作为你的数据模型来查看它会是

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

或者如果在视图中使用 controllerAs 别名:

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

还需要在控制器中注入$http

【讨论】:

  • 这个我知道。问题是,如何在 DemoCtrl 函数中使用 $http 依赖,或者作为参数...
  • 你只需注入它。我想我不明白问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-31
  • 2011-09-14
相关资源
最近更新 更多