2016-07-27 37 views
1

我有一個基本上是一個對象的控制器,並且在那個對象內部我有函數。Angular - 使用ng-click後控制器刷新

在開始時,我設置變量的默認值,並使用init()函數從數據庫中獲取數據。

除了一件事以外,整個頁面都能正常工作。不知怎的,我遇到麻煩時,我用我的NG-點擊選自

<a href="#" ng-click="listCtrl.removeFromChosen(chosen)" class="tagselect__close"> 
    <span class="glyphicon glyphicon-remove remove-icon" aria-hidden="true"></span> 
    </a> 

我的整個控制器再次初始化刪除,因此它設置的所有值設置爲默認,並再次調用init()功能。我無法弄清楚爲什麼會發生這種情況。

"use strict"; 
myApp.controller('ListCtrl', ['$scope', '$cookies', '$http', function ($scope, $cookies, $http) { 

    var listCtrl = { 
     candidate: {}, 
     candidates: [], 
     positions: [], 
     chosenPositions: [], 

     init: function() { 
      listCtrl.getCandidates(); 
      listCtrl.getPositions(); 
     }, 
     getCandidates: function() { 
      $http.get('api/v1/candidates/getCandidates.php').then(function (res) { 
       listCtrl.candidates = res.data; 
      }); 
     }, 
     getPositions: function() { 
      $http.get('api/v1/positions/getPositions.php').then(function (res) { 
       listCtrl.positions = res.data; 
      }); 
     }, 
     removeFromChosen: function (position) { 
      var index = listCtrl.getChosenIndex(position); 
      listCtrl.chosenPositions.splice(index, 1); 
      //console.log(listCtrl.chosenPositions); 
     }, 
    }; 

    listCtrl.init(); 
    $scope.listCtrl = listCtrl; 
}]); 

任何想法我做錯了什麼?

回答

2

當使用錨標記執行點擊功能時,即使它沒有鏈接到任何東西,它會默認刷新頁面。爲了防止這種情況,傳遞事件對象,以您所呼叫的功能及使用方法防止默認像這樣:

removeFromChosen: function (event, position) { 
     event.preventDefault(); 
     var index = listCtrl.getChosenIndex(position); 
     listCtrl.chosenPositions.splice(index, 1); 
     //console.log(listCtrl.chosenPositions); 
    } 
+0

嗨@ Cameron637,感謝漂亮explenation。你是對的 :) – Andurit

2

刪除href="#"與ng-click不兼容。

+0

謝謝你,你是對的:),它解決了我的問題 – Andurit