Problem by declaring a service


#1

I need to pass some data through a service because it is the most logical I found my script is:

angular.module('ionicApp', ['ionic'])

.config(function($stateProvider, $urlRouterProvider) {

 $stateProvider
.state('eventmenu', {
  url: "/event",
  abstract: true,
  templateUrl: "event-menu.html"
})
.state('eventmenu.home', {
  url: "/home",
  views: {
    'menuContent' :{
      templateUrl: "home.html"
    }
  }
})
.state('eventmenu.perfil', {
  url: "/perfil",
  views: {
    'menuContent' :{
      templateUrl: "perfil.html",
      controller: "PerfilCtrl"
    }
  }
})
.state('eventmenu.noticias', {
  url: "/noticias",
  views: {
    'menuContent' :{
      templateUrl: "noticias.html",
      controller: "NoticiasCtrl"
    }
  }
 })
.state('eventmenu.planes_entrenamientos', {
  url: "/planes_entrenamientos",
  views:{
    'menuContent' :{
      templateUrl: "planes_entrenamientos.html",
      controller: "planesEntrenamientoCtrl"
    }
  }
})
.state('eventmenu.rutas_oficiales', {
  url: "/rutas_oficiales",
  views:{
    'menuContent' :{
      templateUrl: "rutas_oficiales.html",
      controller: "rutasOficialesCtrl"
    }
  }
 })

$urlRouterProvider.otherwise("/event/home");
 })

.service('planesService', function() {
 var datos_plan = {};

    return {
        getDatosPlan: function () {
            return datos_plan;
        },
        setDatosPlan: function(data) {
            datos_plan = data;
        }
    };
})

  .controller('MainCtrl', function($scope, $ionicSideMenuDelegate) {
   $scope.attendees = [
    { firstname: 'Nicolas', lastname: 'Cage' },
    { firstname: 'Jean-Claude', lastname: 'Van Damme' },
    { firstname: 'Keanu', lastname: 'Reeves' },
    { firstname: 'Steven', lastname: 'Seagal' }
  ];

  $scope.toggleLeft = function() {
     $ionicSideMenuDelegate.toggleLeft();
     };
  })

.controller('rutasOficialesCtrl',function($scope){

})

.controller('PerfilCtrl', function($scope) {
  $scope.showForm = true;
  var usuario = {};
  usuario = planesService.getDatosPlan();
})

.controller('NoticiasCtrl', function($scope) {

  $scope.activity = [];
  $scope.arrivedChange = function(attendee) {
  var msg = attendee.firstname + ' ' + attendee.lastname;
  msg += (!attendee.arrived ? ' has arrived, ' : ' just left, '); 
  msg += new Date().getMilliseconds();
  $scope.activity.push(msg);
  if($scope.activity.length > 3) {
    $scope.activity.splice(0, 1);
   }
 };
 })

.controller('planesEntrenamientoCtrl', ['$scope','$ionicPlatform', '$location',
  function($scope, $ionicPlatform, $location) {
    $scope.master = {};
    $scope.update = function(user) {
     //Condiciones
     planesService.setDatosPlan(user);
     $scope.master = angular.copy(user);
   };
}])

.directive("appMap", function ($window) {
    return {
        restrict: "E",
       replace: true,
       template: "<div></div>",
       scope: {
          center: "=",        // Center point on the map (e.g. <code>{ latitude: 10, longitude: 10 }</code>).
          markers: "=",       // Array of map markers (e.g. <code>[{ lat: 10, lon: 10, name: "hello" }]    </code>).
        width: "@",         // Map width in pixels.
        height: "@",        // Map height in pixels.
        zoom: "@",          // Zoom level (one is totally zoomed out, 25 is very much zoomed in).
        mapTypeId: "@",     // Type of tile to show on the map (roadmap, satellite, hybrid, terrain).
        panControl: "@",    // Whether to show a pan control on the map.
        zoomControl: "@",   // Whether to show a zoom control on the map.
        scaleControl: "@"   // Whether to show scale control on the map.
    },
    link: function (scope, element, attrs) {
        var toResize, toCenter;
        var map;
        var infowindow;
        var currentMarkers;
        var callbackName = 'InitMapCb';
  } // end of link:
}; // end of return
});

And so far everything works fine unless the declaration of the service, does not throw any error loading the page, but when function call fails and the error is ā€œundefined nombreServicioā€, where Iā€™m going wrong?


#2

I can not find it in your example.
Can you explain where are declaring / using ā€˜nombreServicioā€™ ?


#3

Sorry, that ā€œnombreServicioā€ use it to display the error throwing javascript. The service I declare is ā€œplanesServiceā€ I want to know where Iā€™m wrong.


#4

The error is that you need to pass your ā€˜planesServiceā€™ as a dependecy to the controller where you want to use it. As well as your are passing $scope, $locationā€¦etc

  .controller('PerfilCtrl', function($scope, planesService) {
  $scope.showForm = true;
  var usuario = {};
  usuario = planesService.getDatosPlan();
})

Can you try this way and comment?


#5

He had tried that but I sent the error that the function was not defined.

TypeError: Can not read property ā€˜setDatosPlanā€™ of undefined


#6

Because your controller doenā€™t know what planesService is if it is not correctly injected.

   .controller('planesEntrenamientoCtrl', ['$scope','$ionicPlatform', '$location', 'planesService',
  function($scope, $ionicPlatform, $location, planesService) {
    $scope.master = {};
    $scope.update = function(user) {
     //Condiciones
     planesService.setDatosPlan(user);
     $scope.master = angular.copy(user);
   };
}])

Please notice you have to declare both in the dependencies array and as a function parameter.


#7

Thank you very much, or not throw an error now, but I have a question: Is it good way to pass data to another view? As I can redirect and display the data? Iā€™ll leave the code as I intend to do, but I think Iā€™m wrong.

Controller

.controller('planesEntrenamientoCtrl', ['$scope','$ionicPlatform', '$location','planesService',
  function($scope, $ionicPlatform, $location,planesService) {
    $scope.master = {};
    $scope.update = function(user) {
     //Condiciones
     planesService.setDatosPlan(user);
     $scope.master = angular.copy(user);
  };
}])

.controller('PerfilCtrl', ['$scope','planesService', 
  function($scope,planesService) {
    $scope.showForm = true;
    var usuario = {};
    usuario = planesService.getDatosPlan();
}]) 

<script id="perfil.html" type="text/ng-template">
  <ion-view title="Perfil">
  <pre>form = {{usuario | json}}</pre>
    <div class="bar bar-footer bar-dark">
      <div class="title">Footer</div>
    </div>
  </ion-view>
</script>

    <script id="planes_entrenamientos.html" type="text/ng-template">
  <ion-view title="Planes de entrenamiento" left-buttons="leftButtons">
    <ion-content>
     <form novalidate class="simple-form">
        <div class="list list-inset">
        <label class="item item-input">
          <input type="text" placeholder="Nombres" ng-model="user.name">
        </label>
        <label class="item item-input">
          <input type="text" placeholder="Apellidos" ng-model="user.apellido">
        </label>
        <label class="item item-input item-select">
          <div class="input-label">
            Genero
          </div>
          <select ng-model="user.genero">
            <option>Masculino</option>
            <option>Femenino</option>
          </select>
        </label>
        <label class="item item-input item-select">
          <div class="input-label">
            Distancia
          </div>
          <select ng-model="user.distancia">
            <option>10K</option>
            <option>15K</option>
            <option>20K</option>
          </select>
        </label>
        <button class="button button-block button-positive" ng-click="update(user)">
          Buscar
        </button>
        <a class="button" href="#/event/perfil">Ver Datos</a>
        <pre>form = {{user | json}}</pre>
        <pre>master = {{master | json}}</pre>
       </form>
      </div>
      <app-map style="height:0px;margin:12px;box-shadow:0 3px 25px  black;"center="basel"zoom="15"markers="whoiswhere"> 
      </app-map>       
    </ion-content>
  </ion-view>
</script>

#8

It is a very good way to do this with a service.