javascript - Angular 中的 $http 请求后,链接函数中未定义数据

标签 javascript angularjs

我有以下代码。

controller.js

angular.module('LiveAPP.main',['LiveAPP.factory'])
.controller('mainCtrl', ['$scope','$http', '$location','dataFactory',mainCtrl])

.directive('ratehome',function(){
  return {
    restrict:"E",
    template: "<div id='rateYo'></div>",
    link: function(scope, ele, attrs){
      console.log("NEW",scope.recentArtist)
    }
  }
})


function mainCtrl($scope,$http,$location,dataFactory){

  $scope.getRecentArtists = function(){
     return $http({
        method: 'GET',
        url: '/artistsearch',
        params: {getArtist: "all"}
    }).then(function(recent){
      $scope.recentArtist = recent.data

    })
  };

  $scope.getRecentArtists();

  $scope.recentArtist = ""

  $scope.$watch('recentArtist',function(newValue,oldValue){
    $scope.recentArtist = newValue

  })

}    

test.html

<ratehome></ratehome>
<ratehome></ratehome>
<ratehome></ratehome>

这里发生的情况是在我的 Controller 实例化时(路由设置正确),有一个 $http GET 请求响应我需要的数据,这些数据被分配给 $scope。最近的艺术家。我希望可以在我的链接函数中访问这些数据,但事实并非如此。我有一种感觉,在发送此请求之前我的指令正在编译。有没有办法解决?对我来说奇怪的是,当我 console.log(scope) 并检查 Chrome 开发人员工具时,我的数据就在那里。然而,当我 console.log(scope.recentArtist) 时,它是空的,类似于 Controller 中的状态。我想我也许可以在我的指令中添加 $http.get ,但这对我来说似乎有点尴尬。

我已经被这个问题困扰了几天,希望有人能帮助我。

最佳答案

如果您使用Angular ui-router,您也可以使用resolve。使用resolve,您可以在 Controller 启动之前执行$http

You can use resolve to provide your controller with content or data that is custom to the state. resolve is an optional map of dependencies which should be injected into the controller.

If any of these dependencies are promises, they will be resolved and converted to a value before the controller is instantiated and the $stateChangeSuccess event is fired.

from the docs.

请看看下面的演示或这个 jsfiddle .

angular.module('demoApp', ['ui.router'])
    .config(function ($urlRouterProvider, $stateProvider) {
    $urlRouterProvider.otherwise('/');
    $stateProvider.state('home', {
        url: '/',
        template: '<ratehome></ratehome><ratehome></ratehome><ratehome></ratehome>',
        controller: 'mainCtrl',
        resolve: {
            artists: function (artistsService) {
                console.log('Resolve');
                return artistsService.get(); //'/artistsearch',//artistsService.get();
            }
        }
    });
})
    .controller('mainCtrl', ['$scope', '$http', '$location', 'artists', MainCtrl])

    .directive('ratehome', function () {
    return {
        restrict: "E",
        template: '<div id="rateYo"><ul><li ng-repeat="artist in recentArtist">{{artist}}</li></ul></div>',
        link: function (scope, elem, attrs) {
            console.log("NEW", scope.recentArtist);
        }
    }
})

    .factory('artistsService', function ($http) {
    return {
        get: function () {
            console.log('getting');
            return $http({
                method: 'GET',
                url: 'http://crossorigin.me/http://www.mocky.io/v2/558b30615f3dcbc414067170', //'/artistsearch',
                //params: {getArtist: "all"}
            }).then(function (recent) {
                //console.log(recent);
                return recent.data;
            });
        }
    };
});

function MainCtrl($scope, $http, $location, artists) {

    $scope.recentArtist = artists;
    console.log('ctrl', artists);    

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js"></script>
<div ng-app="demoApp">
    <div ui-view=""></div>
</div>

关于javascript - Angular 中的 $http 请求后,链接函数中未定义数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31037005/

相关文章:

javascript - 循环函数导致它在 javascript 中无响应

jquery - Angular 1.3 和所需的最低 JQuery 版本

javascript - 如何将 Mongoose promise 循环限制为只有几次?

javascript - 如何将数据类型附加到 Cypress.as 别名函数

AngularJS (ng-grid) "editableCellTemplate"在失去焦点时仍处于编辑模式

javascript - 如何设置工具提示 z-index 大于剑道网格标题?

javascript - AngularJS 纯文本解析与一些简单的规则

javascript - 如何使用 Angularjs 显示面包屑

javascript - 为什么 TypeScript 中未定义剩余参数?

javascript - 如果未显示警报则运行函数