ng-repeat 仅在单击另一个选项卡或在文本框中输入后更新

ng-repeat only updating after clicking another tab or typing in a textbox

我是 angular 的新手,在尝试创建基本的 "to-do" 列表类应用程序时遇到了一些问题。

边栏中有各种类别,用户可以单击一个按钮,弹出一个模式提示用户输入新类别的名称。此名称用于创建一个新类别,该类别将被推送到预先存在的数组中。

但是,只有在我开始在屏幕上的另一个文本框中键入内容或单击另一个选项卡后,新类别才会出现。

应该相关的代码:

var list = this;

$(document).on("click", ".prompt", function(e) {
bootbox.prompt("What do you want your new category to be?", function(result) {                
    if(result !== null) {
        list.addCategory(result);
    }
});
});

this.addCategory = function(result) {
  if(result.trim() != "") {
    var newCategory = new Category(result);
    list.categories.push(newCategory);
    this.setCategory(newCategory);
  }
};

我似乎无法弄清楚如何将 post HTML 作为代码块,但这里是用于列出类别的指令(categoryCtrl 是控制器有问题):ng-class="{active: categoryCtrl.isSet(category) }" ng-repeat="category in categoryCtrl.categories" ng-init="categoryCtrl.currCategory = categoryCtrl.categories[0]"

我知道数组正在立即更新 - 如果我添加一个警报 'bootbox.alert(list.categories[list.categories.length-1].name)' 警报会给我任何输入,就像它应该的那样。它只是没有出现在 ng-repeat 中。

另一个有趣的观察结果是 ng-init 覆盖了 this.setCategory(newCategory) - 所以当列表确实更新时,它似乎正在恢复到它的 ng-init 值。

我有一个数组的 ng-repeat 的其他地方,当有新的东西被推到它上面时它会自动更新。我想知道它是否与 bootbox 的 modal/usage 有关 - 其​​他任何地方都是通过复选框或将某些内容键入屏幕上的文本框来添加的,这是唯一使用模态的地方。

这是一个有效的plunker based on your code.

该应用程序如下所示。我在示例中用虚拟数据初始化了一个数组,但空数组也可以。我使用的 vm = this 语法类似于您所拥有的。当调用 $nbBootbox.prompt 时,它 returns 是一个承诺,因此您需要使用 then() 语法,如下所示:

var app = angular.module('plunker', ['ngBootbox']);

    app.controller('MainCtrl', ['$scope', '$ngBootbox', function($scope, $ngBootbox) {
      var vm = this;

      vm.name = 'World';
      vm.categories = ['Category 1', 'Category 2'];

      vm.prompt = function() {

        $ngBootbox.prompt('Enter a new category?')
          .then(function(result) {
            console.log('Prompt returned: ' + result);
            vm.categories.push(result);
          }, function() {
            console.log('Prompt dismissed!');
          });

      }
    }]);

为了让你的 HTML 更 angular 就像我把它改成这样并使用 ControllerAs 语法:

<body ng-controller="MainCtrl as vm">
  <p>Hello {{vm.name}} !</p>
  <ul>
    <li ng-repeat="c in vm.categories">{{c}}</li>
  </ul>
  <a href="" ng-click="vm.prompt()">Add Category</a>
</body>

因此,link 调用 prompt() 函数...它打开模式,如果您输入类别,我将其推送到类别数组,并自动添加到页面中类别列表中的新要点。

From the documentation: $ngBootbox.prompt(消息)

Returns 一个在提交时解决并在驳回时拒绝的承诺。

例子

$ngBootbox.prompt('Enter something')
    .then(function(result) {
        console.log('Prompt returned: ' + result);
    }, function() {
        console.log('Prompt dismissed!');
    });

希望这对您有所帮助。让我们知道。