2016-08-19 54 views
0

我有以下AngularJS代碼。我有一個產品列表,我希望能夠使用一個控制器從列表中定義新的或更新選定的產品。以下是我的代碼。控制器定義塊/主體執行多少次?

當我想編輯列表中的一個產品,我只需撥打:

$scope.EditProduct = function(prodId) { 
    $location.path('/productedit/' + prodId); 
}; 

出於某種原因,newProductController主要定義體被稱爲兩次。我可以看到函數「GetProductForEdit」被調用兩次。我搜索了所有的項目,並且只有一個調用GetProductForEdit。

有人可以解釋爲什麼會發生這種情況?這是AJ中常見的行爲嗎?我究竟做錯了什麼?

非常感謝您的幫助。

Mehdi

我正在使用ngRoute。

http://127.0.0.1:5000/static/pages/index.html#/productedit/1 

myApp.config(function ($routeProvider) { 
    $routeProvider 
     // some more routes 
     ... 
     // route for the product edit page 
     .when('/productedit/:id', { 
      templateUrl: '../pages/productedit.html', 
      controller: 'newProductController' 
     }); 
}); 


myApp.controller('newProductController', ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) { 
    .... 

    $scope.GetProductForEdit = function(prodId) {/* code here is called twice*/}; 

    $scope.Init = function() { 
     if ($routeParams.id != undefined && $routeParams.id != '') { 
      $scope.Operation = 'Update';    
      $scope.GetProductForEdit($routeParams.id); 
     } else { 
      $scope.Operation = 'New'; 
      $scope.CleanupForm(); 
     } 
    }; 

    $scope.Init(); 

}]); 
+0

你可能在你的模板 –

回答

1

刪除您的HTML ng-controller="newProductController",這是使你的控制器運行兩次,你已經設置了控制器在$routeProvider,所以你不需要使用ng-controller指令的唯一案例!

+0

中有'ng-controller =「newProductController」哦......我非常感謝你。我不是問過,我不會找到它的。 – user1941390