質問

My AngularJS app requires some metadata from the server before it can initialize the controller and a handful of directives. I have a service to return the data but have been unable to get the controller and directives to wait for the data.

myapp.factory("db",["$http",function($http)
{
  var db = {};

  db.metadata = function(callback)
  {
    $http.jsonp("/db/?f=metadata&callback=JSON_CALLBACK").success(function(data)
    {
      callback(data);
    }).error(function(error)
    {
      console.log(error);
    });
  }
  ...
  return db;
}]);


var myctrl = myapp.controller("MyCtrl",["$scope","$location","db",function($scope,$location,db)
{
  db.metadata(function(data)
  {
    $scope.metadata = data;
    // initialize $scope members with $scope.metadata for directives
     ...
  });
}]);

This obviously won't work since the directives will attempt to initialize using undefined $scope members before the call to db.metadata() returns. I have tried using the $routeProvider resolve property:

myapp.config(["$routeProvider",function($routeProvider)
{
  $routeProvider.when("/",{
    templateUrl: "./myview.html",
    controller: "MyCtrl",
    resolve: {
      metadata: ["db","$q",function(db,$q)
      {
        var deferred = $q.defer();

        db.metadata(function(data)
        {
          deferred.resolve(data);
        });

        return deferred.promise;
      }]
    }
  });
}]);

var myctrl = myapp.controller("MyCtrl",["$scope","$location","db","metadata",function($scope,$location,db,metadata)
{
  $scope.metadata = metadata;
  // initialize $scope members with $scope.metadata for directives
  ...
}

This doesn't run as the minification friendly declaration of "metadata" in the injection array causes Angular to puke. Removing the declaration results in the injected metadata to be undefined. What am I doing wrong?

役に立ちましたか?

解決

The problem turned out to be that the html still had

<div ng-controller="MyCtrl">

It's not needed since "MyCtrl" was assigned the controller for myview.html via the $routeProvider config.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top