【问题标题】:Angular - Controller refresh after using ng-clickAngular - 使用 ng-click 后控制器刷新
【发布时间】:2016-07-27 15:50:59
【问题描述】:

我有一个控制器,它基本上是一个对象,在该对象内部我有功能。

一开始我设置变量的默认值并使用init() 函数从数据库中获取数据。

整个页面都可以正常工作,除了一件事。当我使用 ng-click 从所选内容中删除时,不知何故我遇到了麻烦

  <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;
}]);

知道我做错了什么吗?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    当使用锚标签执行点击功能时,即使它没有链接到任何东西,它也会默认刷新页面。为了防止这种情况发生,请将事件对象传递给您正在调用的函数并使用 prevent default ,如下所示:

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

    【讨论】:

    • 嗨@Cameron637,感谢您的精彩解释。你是对的:)
    【解决方案2】:

    删除与ng-click不兼容的href="#"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-15
      相关资源
      最近更新 更多