2016-12-18 4 views
2

У меня есть navbar, который показывает несколько country names, и когда вы нажимаете на них, то должно появиться соответствующее сообщение map.Передача аргумента в пользовательскую директиву в AngularJS

<nav class="navbar navbar-default"> 
    <div class="container-fluid"> 
     <div class="navbar-header"> 
      <a class="navbar-brand" href="#">Welcome to the world of directives!</a> 
     </div> 
     <ul class="nav navbar-nav"> 
      <li ng-repeat="countryTab in countries" ng-clicked="itemClicked(countryTab)" style="cursor:pointer"> 
       <a>{{countryTab.label}}</a></li> 
     </ul> 
    </div> 
</nav> 

И array of countries сейчас жестко закодирован.

var app = angular.module('app',[]); 
    app.controller('appCtrl',function($scope){ 
     // Countries 
     $scope.countries = [{ 
      id: 1, 
      label: 'Italy', 
      coords: '41.29246,12.5736108' 
     }, { 
      id: 2, 
      label: 'Japan', 
      coords: '37.4900318,136.4664008' 
     }, { 
      id: 3, 
      label: 'USA', 
      coords: '37.6,-95.665' 
     }, { 
      id: 4, 
      label: 'India', 
      coords: '20.5937,78.9629' 
     }]; 
    }); 

custom directive, который должен показать соответствующую карту сейчас, как:

<div> 
    <country-tab-bar></country-tab-bar> 
</div> 

И

app.directive('countryTabBar',function(){ 
     return { 
      restrict: ';E', 
      template: '<div>'+ 
          ' <div>Italy</div>'+ 
          ' <br/>'+ 
          ' <img ng-src="https://maps.googleapis.com/maps/api/staticmap?center=41.29246,12.5736108&zoom=4&size=800x200"> '+   
          '</div>', 
      link : function(scope){ 
       scope.itemClicked = function(value){ 
       } 
      } 
     } 
    }); 

As it is hard coded coordinates , it only shows one map of Italy. But I want to make it to show respective maps passing coordinates .

Также имя в div должно измениться, чтобы отразить нынешний ку ntry.

enter image description here

Как добиться того же?

Просьба предоставить необходимое объяснение.

+0

Его похожее на ваш последний вопрос, не вы смотрели на [этот ответ] (http://stackoverflow.com/a/41207875/2435473), предоставленный мне (я думаю, вероятно, это решит вашу проблему). Вы не должны задавать один и тот же вопрос несколько раз без причины .. –

+0

@PankajParkar Большое спасибо. Не могли бы вы объяснить, что такое «город» в объекте «scope» и что именно вы пытаетесь сделать в функции ссылок? – StrugglingCoder

ответ

0

Вы можете достичь желаемого, как показано ниже

вам нужно передать ярлык страны и страна COORDS из HTML в директиве первой.

<country-tab-bar coords="countryTab.coords" country="countryTab.label"></country-tab-bar> 

Получить значения в области действия директивы.

 scope: { 
      coords: '=coords', 
      country: '=country', 
     } 

в разделе ссылок используйте эти члены сферы охвата и обновите URL-адрес шаблона. добавьте это к элементу (это тег html, в котором применяется директива). и, наконец, скомпилировать его.

var app = angular.module('app',[]); 
 
    app.controller('appCtrl',function($scope){ 
 
     // Countries 
 
     $scope.countries = [{ 
 
      id: 1, 
 
      label: 'Italy', 
 
      coords: '41.29246,12.5736108' 
 
     }, { 
 
      id: 2, 
 
      label: 'Japan', 
 
      coords: '37.4900318,136.4664008' 
 
     }, { 
 
      id: 3, 
 
      label: 'USA', 
 
      coords: '37.6,-95.665' 
 
     }, { 
 
      id: 4, 
 
      label: 'India', 
 
      coords: '20.5937,78.9629' 
 
     }]; 
 
    }); 
 

 
app.directive('countryTabBar', function($compile){ 
 
     return { 
 
      restrict: ';E', 
 
      scope: { 
 
      coords: '=coords', 
 
      country: '=country', 
 
      }, 
 
      link : function(scope,element){ 
 
       
 
       var template = '<div ng-click="show()">'+scope.country+'</div><img ng-src="https://maps.googleapis.com/maps/api/staticmap?center='+scope.coords+'&zoom=4&size=800x200">'; 
 
       
 
      element.append(template); 
 
       
 
      $compile(element.contents())(scope); 
 
       
 
      } 
 
     } 
 
     });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<body ng-app="app" ng-controller="appCtrl"> 
 
<nav class="navbar navbar-default"> 
 
    <div class="container-fluid"> 
 
     <div class="navbar-header"> 
 
      <a class="navbar-brand" href="#">Welcome to the world of directives!</a> 
 
     </div> 
 
     <ul class="nav navbar-nav"> 
 
      <li ng-repeat="countryTab in countries" style="cursor:pointer"> 
 
      
 
      <country-tab-bar coords="countryTab.coords" country="countryTab.label"></country-tab-bar> 
 
      
 
      </li> 
 
      
 
     </ul> 
 
    </div> 
 
</nav> 
 

 
</body>

Смежные вопросы