0

I called method console.log(data) in my controller only once but the output in console is displayed twice.

enter image description here

This is the controller:

taskAppControllers.controller('ToDoCtrl', ['$scope',
  function($scope){
    $scope.loadToDoItems = function(){
      var data = ls.get("toDoData");
      if (data == null) data = [];
      console.log(data);
    }
    $scope.toDoItems = $scope.loadToDoItems();
    $scope.addToDoItem(){};
}]);

And this is the view:

<div ng-controller="ToDoCtrl">
  <form>
    <input type="text" ng-model="toDoItem">
    <input type="submit" ng-click="addToDoItem()">
  </form>
</div>

The router:

var TaskApp = angular.module('TaskApp', [
  'ngRoute',
  'taskAppControllers'
]);

TaskApp.config(['$routeProvider',
  function($routeProvider){
  $routeProvider.
      when('/home', {
        templateUrl: "partials/home.html",
        controller: "HomeCtrl",
        title: 'Home',
        icon: 'ion-android-menu',
        link: '#/main-menu'
      }).
      when('/main-menu', {
        templateUrl: "partials/main-menu.html",
        controller: "MainMenuCtrl",
        title: 'Main menu',
        icon: 'ion-close',
        link: '#/'
      }).
      when('/todo', {
        templateUrl: "partials/todo.html",
        controller: "ToDoCtrl",
        title: 'To do',
        icon: 'ion-close',
        link: '#/main-menu'
      }).
      otherwise({
        redirectTo: "/home"
      });
  }]);
8
  • $scope.loadToDoItems() doesn't return anything. Presumably you're calling or triggering it somehow other than $scope.toDoItems = $scope.loadToDoItems() which runs when your controller is created. Can't see an addToDoItem() method on your $scope either Commented Mar 30, 2016 at 1:48
  • @Phil Yeah because I deleted it temporary. Commented Mar 30, 2016 at 1:49
  • Where else do you call loadToDoItems()? How is the view loaded / included? Commented Mar 30, 2016 at 1:52
  • @Phil it is included as partial. This is the only place it is called. If I rename it to for example toDoItems423412423423 , nothing really changes, it still gives double output, so I am pretty sure it's called only once. Commented Mar 30, 2016 at 1:55
  • 2
    That view is rendered twice. Use console.log("I am called") as controller first line which will confirm you the controller is called twice. Then its your routing issue Commented Mar 30, 2016 at 2:14

1 Answer 1

2

You should not use ng-controller in your HTML because you are using routing. You should use ng-view.

Check the routing documentation, like here.

Maybe your controller is being executed once from the HTML and once from the router.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.