1. 程式人生 > >指令的互動與ajax異步出現的問題

指令的互動與ajax異步出現的問題

我們知道如果不給指令設定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結束以後,屬性不是空了

就渲染了

因此,問題得到解決