2016-02-12 57 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: '=' 
    }, 

如果你把这个模型附加属性,他们会从那里你叫控制器可见。