angular 获取变量后加载指令

angular directive load after got variables

我有一个 angular 从服务加载数据的指令, 但 它使用一个变量加载数据,该变量来自控制器,该控制器也是从服务加载的。

代码: 指令:

app.directive("posts", ['Posts', function(Posts) {
return {
    restrict: 'E',

    template: '' +
    '<div ng-repeat="post in posts"></div>',
    scope: {
        showLoading: '&',
        hideLoading: '&',
        spot: '@'
    },

    controller: ['$scope', function ($scope) {

    }],

    link: function(scope, element, attrs) {
         $scope.load = function () {
            Posts.loadPostsBySpot(scope.spot)
        };
    }
};
}]);

控制器

app.controller('spotPageController', ['$scope', 'Spots', function ($scope, $Spots) {

    doit = function () {
        Spots.getSpot($)
            .success(function (data) {
                $scope.spotId = data.data;
                console.log($scope.spot);
            }).error(function (data) {
                console.log('error');
            });
    };
 }]);

html里面

<posts spot="{{spotId}}" showLoading="showLoading()" hideLoading="hideLoading()"></posts>

但是当加载指令时 "spot" 尚未设置, 那么如何让指令仅在设置点后加载。

使用ng-if.

<posts ng-if="spotId" spot="{{spotId}}" showLoading="showLoading()" hideLoading="hideLoading()"></posts>

只有在 spotId 初始化后才会呈现此元素。因此,您的指令在此之前不会被调用。

如果你想在指令中封装这个行为,你应该注意scopeId的变化。见 fiddle.