【问题标题】:How to pass data with Angularjs如何使用 Angularjs 传递数据
【发布时间】:2021-04-03 22:21:13
【问题描述】:

如何将数据从控制器传递到组件以显示给用户?

app.js

(function(angular) {
    'use strict';
  angular.module('app', []).controller('MainCtrl', function MainCtrl($scope, $http) {

    $http({
      method: 'GET',
      url: '/team',
    }).then(function successCallback(response) {
      console.log(response.data);
      this.teams = response.data;
      $scope.teams = response.data;
      // var keys = Object.keys($scope.agendaEventData);
      // $scope.eventslength = keys.length;
      
    }, function errorCallback(response) {
    });
      
  }).config(['$httpProvider', function($httpProvider) {
      $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
    }]);
  })(window.angular);

组件

(function(angular) {
  'use strict';
angular.module('app').component('bringTeamToEvent', {
  templateUrl: '/assets/ng/app/team/bringTeamToEvent.html',
  bindings: {
    teams: '<'
  },
  
});
})(window.angular);

模板

{{$ctrl.teams}}
{{teams}}

数据来自 api 没有问题,我不明白让它工作的复杂性。 向https://docs.angularjs.org/tutorial/step_13学习 和https://docs.angularjs.org/guide/component#

【问题讨论】:

    标签: javascript angularjs angularjs-controller angularjs-components


    【解决方案1】:

    this.teams 上设置数据是正确的,并且像$ctrl.teams 一样访问它是正确的。这里的问题是您的 $http 回调函数正在注入它们自己的函数上下文,因此 this 不会引用该组件。

    因此,将arrow functions 用于回调函数通常是一种很好的做法:

    $http({
      method: 'GET',
      url: '/team',
    }).then(response => {
      this.teams = response.data;
    }, response => {
    });
    

    这是demo

    【讨论】:

      猜你喜欢
      • 2014-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-08
      相关资源
      最近更新 更多