Pregunta

I have the following example:

var loadUserWidget;

loadUserWidget = function() {
  console.log(Restangular.one());
  if (!$scope.i) {
    $scope.i = 0;
  }
  console.log($scope.i);
  return $scope.i = $scope.i + 1;
};

loadUserWidget()

and I get the following console.log

Object {id: undefined, route: undefined, getRestangularUrl: function, getRequestedUrl: function, addRestangularMethod: function…} cache_list_controller.js?body=1:276

0 cache_list_controller.js?body=1:280

Object {id: undefined, route: undefined, getRestangularUrl: function, getRequestedUrl: function, addRestangularMethod: function…} cache_list_controller.js?body=1:276

1 cache_list_controller.js?body=1:280

You can see that the restangular method is being fired twice and i can't seem to identify why.

Update:

Contorller:

bbControllers.controller('CacheListController', [
  '$scope', 'Restangular', '$rootScope', 'Snippet', '$modal', '$templateCache', "$window", 'Widget', '$sce', '$location', function($scope, Restangular, $rootScope, Snippet, $modal, $templateCache, $window, Widget, $sce, $location) {
    var loadUserWidget;
    loadUserWidget = function() {
      console.log(Restangular.one());
      if (!$scope.i) {
        $scope.i = 0;
      }
      $scope.i = $scope.i + 1;
      return console.log($scope.i);
    };
    return loadUserWidget();
  }
]);

app.js

var bbPlnkr = angular.module('BBPlnkr', ['BB', 'restangular', 'ngRoute', 'xeditable', 'ngSanitize']);

bbPlnkr.config(function ($routeProvider, $locationProvider, RestangularProvider) {
    $routeProvider
        .when('/edit', {
            templateUrl: '../assets/index.html',
            controller: 'CacheListController',
            reloadOnSearch: false
        })
        .when('/edit/:id', {
            templateUrl: '../assets/index.html',
            controller: 'CacheListController'
        })
        .when('/invitation/:url', {
            templateUrl: '../assets/invitation-detail.html',
            controller: 'InvitationController'
        })
        .otherwise({
            redirectTo: '/edit'
        });
    $locationProvider.html5Mode(true);
});
¿Fue útil?

Solución

When using both the ng-controller directive in the template and declaring routes using $routeProvider there will be two instances of the controller, and they will both fire a Restangular request.

If you do

connsole.log($scope.$id);

You should be seeing two different values since there are two different controllers.

Don't use ng-controller when you are using $routeProvider.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top