gpt4 book ai didi

javascript - 获取变量后加载 Angular Directive(指令)

转载 作者:行者123 更新时间:2023-11-28 19:26:07 25 4
gpt4 key购买 nike

我有一个从服务加载数据的 Angular Directive(指令),但它使用从 Controller 加载的变量来加载数据,该变量也是从服务加载的。

代码:指令:

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)
};
}
};
}]);

Controller

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>

但是当加载指令时,“点”尚未设置,那么如何使指令仅在设置位置后加载。

最佳答案

使用ng-if .

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

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

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

关于javascript - 获取变量后加载 Angular Directive(指令),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27857362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com