【问题标题】:Load remote data from an AngularJS directive从 AngularJS 指令加载远程数据
【发布时间】:2014-03-24 15:29:24
【问题描述】:

我有 jQuery 的背景,但我正在尝试使用我正在构建的天气 Web 应用程序来学习 AngularJS。我在页面顶部有 4 个选择框,其中包含城市列表。每个选择框对应于下方的一个天气容器,该容器显示该选定城市的当前天气。

我正在为天气容器使用指令,如下所示。这是构建它的正确方法吗?

<weather city="select1"></weather>
<weather city="select2"></weather>
<weather city="select3"></weather>
<weather city="select4"></weather>

当我从选择框 #1 中选择 ATL 时,它会在选择 1 的天气容器中显示 ATL。那部分有效。但现在我需要它到服务器并获取将在该指令中显示的天气数据。我有一个 API 工作,我可以将 ATL 传递给它,它以 JSON 形式返回天气数据。这样做的正确角度方式是什么?我在指令中找不到调用我的服务的位置,比如 ui-router 有 resolve。谢谢。

【问题讨论】:

    标签: json angularjs angularjs-directive


    【解决方案1】:
    angular.module('yourApp')
        .directive('weather', ['$http', function ($http) {
            template: '<div data-ng-click="getWeather()">{{weatherData}}</div>',
            scope: {
                city: '='
            },
            controller: function(scope) {
                scope.getWeather = function() {
                    $http.get('/your-weather-api?city=' + scope.city)
                        .success(function(data) {
                            scope.weatherData = data;
                        });
                }
            }
        }]);
    

    类似的方法可能会奏效,但我认为这不是构建项目的最佳方式。您能否发布您的代码或最好是 plnkr,我们或许可以提供更多帮助?

    这是一个 plnkr,它显示了一种粗略的方法,可能比您所追求的更容易管理: http://plnkr.co/edit/XcjkfOpuiaasGWa3C0Lv?p=preview

    【讨论】:

      猜你喜欢
      • 2015-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多