当 ajax 调用结束时,将数据传递给 angularjs 中新创建的指令

Passing data to newly created directive in angularjs when ajax call is over

我正在尝试使用平滑网格创建自定义指令。这是我到目前为止所做的。

angular.module('app')
  .directive('myGrid',function () {
      return {
        restrict: 'E',
        link: function (scope, el, attrs) {

          var data = [];
          var columns = [
            {id: "title", name: "Title", field: "title", width: 160, cssClass: "cell-title", editor: Slick.Editors.Text},
            {id: "desc", name: "Description", field: "description", width: 400, editor: Slick.Editors.LongText},
            {id: "duration", name: "Duration", field: "duration",minWidth: 160, editor: Slick.Editors.Text},
            {id: "start", name: "Start", field: "start", minWidth: 160, editor: Slick.Editors.Text},
            {id: "finish", name: "Finish", field: "finish", minWidth: 160, editor: Slick.Editors.Text}

          ];

            scope.grid = new Slick.Grid(el, scope.data, columns, scope.gridOptions);
        }
    }
 });

这就是我使用指令的方式!!

 <my-grid id="myGrid" style="height:500px;" grid-options="gridOptions" ></my-grid>

这是我的控制器

$http.get(url)
            .success(function(response, status, headers, config) {
              $scope.data = response.data;
         });

问题是在 http 调用结束后,我在网格中看不到任何数据。

这是因为您的控制器和指令都是并行执行的。

您需要的是让指令等待控制器完成其 API 调用。

您可以在使用 $emit 的帮助下实现这一点。

在控制器中,

var response = some_json;
$scope.$emit('controllerUpdate', response);

在指令中,用

括起你的代码
$scope.$on('controllerUpdate',function(event, response){
    // Do your work here
});