Question

I am new to angularjs, and I have been reading a ton of documentation and reading through various articles and tutorials as well as videos to help me figure this stuff out. I am trying to get two directives to interchange information between themselves. a really simplified version of what i am trying to do is at odetocode (http://odetocode.com/blogs/scott/archive/2013/09/11/moving-data-in-an-angularjs-directive.aspx) where k scott allen has wrapped his directives with a div that has the ng-controller attribute it works beautifully.

I have a slightly more complex test I am working on, and I am trying to get it to work similarly to the code I have mentioned.

my two directives talk to each other when I list the ng-controller attribute in the actual template for each directive. it works, but I don't think it is correct. the actual controller code is run twice, once for each directive. when I move the controller into the div that wraps the two directives, the two directives stop interacting (the change event in the location-selector template doesn't change the park in the controller). I am pretty sure it has something to do with the scope. if anyone can point me in the right direction, or where I should look for information, that would be much appreciated.

here is my fiddle showing my code http://jsfiddle.net/jgbL9/25/

<div ng-app="myApp">
    <location-selector ></location-selector ><br/>
    <portal-map ></portal-map >
</div>


    var App = angular.module('myApp', ['ngResource']);

    App.directive('locationSelector',['parkList', function(parkList) {
      return {
        restrict: 'E',
        scope: {
          parkId : '=',
          parkName : '='
        },
        template: '<select ng-controller="portalMapCtrl"'+
             ' ng-model="listParks" ng-change="changePark()" '+
             ' park-id="parkId" park-name="parkName" ' +
             ' ng-options="park as park.attributes.NAME for park in Parks" >'+
             '</select>',
        link: function (scope,element,attrs){
          parkList.getListFromGIS().success(function(data) {
            scope.Parks = data.features;
          });
        }
      };
    }]);

    App.directive('portalMap', function(){
      return {
        restrict: 'E',
        scope:{
          parkId: "=",
          parkName: "="
        },
        template: '<style type="text/css" media="screen">'+
            '#mapCanvas {height: 500px; width:75%; border:thin black solid; }'+
            '</style>'+
            '<div id="mapCanvas" park-id="parkId" park-name="parkName"  ng-controller="portalMapCtrl" ></div>'
      }
    });


    App.controller('portalMapCtrl',['$scope','parkList', function( $scope, parkList ){
      var map = {};
      var STREETMAPSERVICE = "https://gis.odot.state.or.us/ArcGIS/rest/services/BASEMAPS/Basemap_Streets/MapServer";
      var FOTOSSERVICE = "https://maps.prd.state.or.us/arcgis/rest/services/ESRI_TEST/MapServer?f=jsapi";
      var UTILSSERVICE = "http://gis.prd.state.or.us/ArcGIS/rest/services/OPRDAssets/MapServer";
      var UTILSSERVICE_PARKLAYER = 0;
      var UTILSSERVICE_STRUCTUREPOLY = 7;
      var UTILSSERVICE_SURFACE = 11;
      var UTILSSERVICE_PARCELS = 12;
      var timer;
      var ALL_LAYERS = [UTILSSERVICE_PARKLAYER,UTILSSERVICE_STRUCTUREPOLY,UTILSSERVICE_SURFACE,UTILSSERVICE_PARCELS];
      $scope.parkId = 0;
      $scope.parkName = "";
      $scope.changePark = function (){
        require(["esri/SpatialReference","esri/geometry/Polygon"],
          function(SpatialReference,Polygon){
            console.log('change park');
            $scope.parkId = $scope.listParks.attributes.PARK_HUB_ID;
            $scope.parkName = $scope.listParks.attributes.NAME;
            parkList.getParkFromGIS($scope.parkId).then(function(data){
               var x = data.data;
               var y = x.features[0];
               var rings = y['geometry'];
               var poly = new Polygon(rings);
               var xtnt = poly.getExtent();
               var sr = new SpatialReference({wkid:2992});
               xtnt.setSpatialReference (sr);
               map.setExtent(xtnt,true);
            });
          });
         };
       function addService(srvc, srvcType, lyrId){require([
               "esri/layers/ArcGISTiledMapServiceLayer",
                "esri/layers/ArcGISDynamicMapServiceLayer",
                "esri/layers/ImageParameters"], function(Tiled,Dynamic,Parameters){
           var mapService = {};

           if(srvcType == 'Tiled'){
             mapService = new Tiled(srvc);
           }else{
             var imageParameters = new Parameters();
             imageParameters.layerIds = lyrId;
             imageParameters.transparent = true;
             mapService = new Dynamic(srvc,{"imageParameters":imageParameters});
           }
           map.addLayer(mapService);
          });
        }

      function createMap(){
        require(["esri/map"],function(Map){
          console.log('create map');
          map = new Map("mapCanvas");
          addService(STREETMAPSERVICE,'Tiled');
          addService(FOTOSSERVICE,'Tiled');
          addService(UTILSSERVICE,'Dynamic',ALL_LAYERS);
        });
      }
      createMap();

   }]);


   App.factory('parkList',['$http', function($http) {
     return {
       getListFromGIS: function() {
         var myUrl = 'http://maps.prd.state.or.us/arcgis/rest/services/ESRI_TEST/MapServer/0/query?where=OBJECTID+%3E+0&geometryType=esriGeometryEnvelope&spatialRel=esriSpatialRelIntersects&outFields=PARK_HUB_ID%2CNAME&returnGeometry=false&&returnIdsOnly=false&returnCountOnly=false&orderByFields=NAME&returnZ=false&returnM=false&returnDistinctValues=true&f=pjson&callback=JSON_CALLBACK';
         return $http ({ url: myUrl, method: 'JSONP'});
        },
        getParkFromGIS: function (id){
          var myUrl = "http://maps.prd.state.or.us/arcgis/rest/services/ESRI_TEST/MapServer/0/query?where=PARK_HUB_ID%3d"+id+"&f=pjson&callback=JSON_CALLBACK";
          return $http ({ url: myUrl, method: 'JSONP'});
        },
        JSON_CALLBACK: function(data) {}
     };
    }]);

(this is the code working with the ng-controller listed in the template of each directive).

any other comments or suggestions you would like to offer about my code structure or code choices will be appreciated also, as I mentioned, I am learning, and the more I can learn the more fun I will have coding.

Was it helpful?

Solution

I believe you're having problems due to your isolate scopes on your directives (the scope: { } in your link function).

I would suggest inlining the templates into your application, instead of trying to make them directives.

In particular, the locationSelector is going to be hard to make a directive - it's usually easier to have your input elements be a part of the element their controller is on.

If you did want to have them be a directive, I'd suggest passing the listParts value into the changePark function:

<select ... ng-change="changePark(listParks)" ...>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top