您的位置:首页 > Web前端 > AngularJS

指令的交互与ajax异步出现的问题

2017-11-30 18:59 281 查看
我们知道如果不给指令设置scope得话我们的指令的scope是跟父scope一致的

这个有一个好处

就是如果我们要把一个模型作为指令的属性的参数传递给质量是ok的,所以我们编写公用的指令,不知道父指令用有什么属性的时候就不设置就好了

但是,如果我们父指令中的某个模型是在ajax异步请求以后才完成的,那么因为我们的指令已经渲染成功了,如果我们的这个传入的属性是决定指令渲染的,那么我们的指令的渲染就不会再次改变,导致失效

.directive('star',
function () {
// 星级评分指令
return {
template: "<i class=\"icon ion-ios-star\" ng-repeat=\"
star in stars\"></i>",
// scope:{"="},
link: function ($scope,
element, attrs) {
// 设置star的次数
console.log($scope);
$scope.stars = [];
console.log(attrs.stars);
while (attrs.stars) {
$scope.stars.push({});
attrs.stars--;
}
}
}
})

现在有一个星级评分的指令

如果我们是使用

他的父scope是这样的

unction ($scope,
$http, $ionicLoading) {
$scope.weatherInfo = {};
$ionicLoading.show();
$http.get('http://localhost:8100/views/weather/weather.json').success(function
(data) {
$scope.weatherInfo =
data;
$ionicLoading.hide();
}).error(function () {
console.log("error");
$ionicLoading.hide();
});

如果我们是用

<star
stars="{{weatherInfo.recommendationRate}}"></star>

因为指令的渲染先于ajax

所以最后的时候我们的指令接受到的stars是空的

也就渲染不出来

但是如果是

<star
stars="{{weatherInfo.recommendationRate}}"
ng-if="weatherInfo.recommendationRate"></star>

那么得话

一开始的时候因为是空,所以不渲染,等到ajax结束以后,属性不是空了

就渲染了

因此,问题得到解决
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息