2016-02-12 51 views
2

這裏我試圖加載一個微調,而一個獲取請求訪問數據,然後顯示消息'獲取請求完成'一旦請求完成。如何在指令和查看頁面之間共享一個範圍變量?

這是我正在試圖切換顯示:

<span ng-show="!isFinishedLoading"> 
    <img src="http://www.broadwaybalancesamerica.com/images/ajax-loader.gif"> 
    </span> 

    <span ng-show="isFinishedLoading"> 
    Get Request completed 
    </span> 

但變量isFinishedLoading不在範圍之內。

如何根據作用域變量切換微調器和請求之間的關係?

plunkr:https://plnkr.co/edit/F0XsOPZKq5HArFo9vtFs?p=preview

源:

2. http-hello2.html 

<!doctype html> 
<html ng-app="app"> 
    <head> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script> 
    <script src="script.js"></script> 
    </head> 
    <body> 

    <div ng-controller="FetchCtrl"> 

<label>Filter: <input ng-model="search"></label> 

<div ng-repeat="sourceUrl in sourceUrls | filter:search track by $index "> 

    <status-viewer url="sourceUrl"> </status-viewer> 


    <span ng-show="!isFinishedLoading"> 
    <img src="http://www.broadwaybalancesamerica.com/images/ajax-loader.gif"> 
    </span> 

    <span ng-show="isFinishedLoading"> 
    Get Request completed 
    </span> 

    </div> 



</div> 


    </body> 
</html> 


<!--<h1>{{url}}</h1>--> 
<div> 
    <p>{{model}}</p> 

</div> 

var myapp = angular.module('app', []).controller('FetchCtrl', FetchCtrl) 

myapp.directive('statusViewer', function ($http , $interval) { 
      return { 
       restrict: 'E', 
       templateUrl: 'mytemplate.html', 
       scope: { 
        url: '=' 
       }, 
       link: function (scope, elem, attrs, ctrl) { 

        console.log('invoked') 


        scope.isFinishedLoading = false; 

        $http.get(scope.url).success(function (data) { 
         scope.model = data; 
         scope.isFinishedLoading = true; 
        }); 
       } 
      }; 
     }); 

function FetchCtrl($scope, $http, $q , $parse) { 


$scope.sourceUrls = [ 
       'http-hello2.html' 
      ,'http-hello2.html']; 



} 

回答

0

我會公開一個範圍,其在該指令,這裏的工作demo

公開範圍,如:

scope: { 
    url: '=', 
    isFinishedLoading: '=' 
}, 

所以模板看起來像:

<status-viewer url="sourceUrl" is-finished-loading='isFinishedLoading'> </status-viewer> 

<span ng-show="!isFinishedLoading"> 
<img src="http://www.broadwaybalancesamerica.com/images/ajax-loader.gif"> 
</span> 

<span ng-show="isFinishedLoading"> 
    Get Request completed 
</span> 

</div> 

所以你FetchCtrl小號isFinishedLoading現在是你的status-viewer適適用範圍內界定雙向的。

0

Working Plunkr

您需要通過指令範圍共享變量。你也可以在指令內顯示微調,如果你不需要它們,會讓事情變得更簡單。

scope: { 
    url: '=', 
    model: '=' 
    }, 

如果你把這個模型附加屬性,他們會從那裏你叫控制器可見。