如何在指令和视图页面之间共享范围变量?

时间:2016-02-12 08:47:47

标签: angularjs

这里我试图在get请求访问数据时加载一个微调器,然后在get请求完成后显示“Get Request completed”消息。

这就是我试图切换显示的方式:

    <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

src:

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'];



} 

2 个答案:

答案 0 :(得分: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范围内双向限制了。

答案 1 :(得分:0)

Working Plunkr

您需要通过指令范围共享变量。你也可以在指令中显示微调器,如果你不需要它们,会使事情变得更容易。

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

如果在该模型上添加其他属性,则可以从调用控制器的位置看到它们。