Angularjs: 指令可以看到它的作用域,但它不能在其中获取单个变量

Angularjs: directive sees its scope but it's not able to take a single variable in it

我因为指令的奇怪行为而变得疯狂。这是一个非常标准的,它获取从 DB 提供的参数。当然,来自数据库的数据是使用承诺的令牌:

//opening of directive and definition of controller
   return {
        restrict: 'EA',
        scope: {
            dateFromPromise: '=',  //a Date() object
            timeFromPromise: '=',  //a Date() object
            booleanFromPromise '='
        },
        templateUrl: 'abc/abc.html',
        controller: AController,
        controllerAs: 'aController'
    };
 //closing of directive

现在,有些变量是看不到的,即使它们都来自同一个承诺。

如果我尝试打印 $scope.booleanFromPromise 没问题,但我无法打印 $scope.dateFromPromise 和 $scope.timeFromPromise(未定义)。也许是因为它需要更多的时间来创建?

如果我 运行 使用 F12 的浏览器,我会在控制台中看到以下内容作为 console.log($scope) 的结果;一切都已定义且正确,如我所愿:

$scope:
n {
    ...
    booleanFromPromise: true
    dateFromPromise: Date {Tue May 24 2016 10:12:00 GMT+0200 (Central European Standard Time)}
    timeFromPromise: Date {Tue May 24 2016 10:12:00 GMT+0200 (Central European Standard Time)}
}

因此日期存在且正确,至少 我通过控制台使用 js 这种不合逻辑的语言进行打印。

怎么做才能:

  1. 获取全部来自promise
  2. 的数据
  3. 只有 步骤 1. 完成后,将数据传递给带有指令的标签,这将看到所有内容。
  4. 了解为什么该指令在其自己的范围内看到所有变量,但它不能在其中获取单个日期,即使已设置也是如此。

谢谢

您可以做几件事。

首先,按照@Jacky Coogan 的建议在您的指令中使用手表,这样您就可以看到模型何时更改。

其次,您说您从 promise 中获取所有数据,因此您可以这样做:

res.$promise.then(function (data) {
                deffered.resolve(data);
                $scope.dataLoaded = true;
            });

然后在您使用指令的 html 中,放置类似这样的内容

<div ng-if="dataLoaded">
   <your-directive booleanFromPromise="xxx" dateFromPromise="yyy" timeFromPromise="zzz" ></your-directive>
</div>

这样,您将能够确保您的指令已使用已加载的数据进行初始化。

或者,您可以使用“controllerResolver”代替上述方法,以确保您的数据在控制器初始化时加载,那么您将不需要$scope.dataLoaded。例如这样的事情:

app.factory("someControllerResolver", ["someService",function (someService) {

       return {
            resolve: function () {
                var deferred = $q.defer();

                someService.getSomething({}, function (res) {                        
                    deferred.resolve(res.data);
                });

                return deferred.promise;
            }
        };

        return {
            resolve: resolve
        };

    }]);

    app.controller("someController", ["dataContext",function (dataContext) {
        $scope.yourData = dataContext;
    ...

尝试上述方法之一,然后您的指令应该正确加载您的数据。

如果不是,则深入研究从服务器返回的内容。如果从服务器返回的数据没有问题,那么您可能在将值传递给指令的方式上犯了错误。

希望对您有所帮助。