一次绑定:更新模型并重新渲染视图

时间:2015-07-07 14:14:52

标签: angularjs data-binding

我想知道是否可能,使用角度一次性绑定,在模型更新后完全重新渲染视图/模板,也可以通过重新编译模板。 例如,在按下按钮时,可能在反应方式中工作:我更新模型并明确强制更新视图。 基本上这就是我想要实现的目标:

// controller
angular.module('app', []).controller('AppCtrl', function($scope) {
    $scope.items = [
        {id: 1},
        {id: 2},
        {id: 3}
    ];

    $scope.addAndRefresh = function() {
        $scope.items.push({id: 4});
        // manually call render logic here???
    };
});


<!-- HTML template -->
<div ng-repeat="item in ::items">
    {{item.id}}
</div>
<button ng-click="addAndRefresh()">Add</button>

点击“添加”按钮,我想刷新视图以查看新添加的项目。

2 个答案:

答案 0 :(得分:11)

我试图想办法优雅地做到这一点。我希望框架内置一些内容来刷新一次性绑定。我想出的就是使用ngIf删除我想要刷新的元素并将其添加回来。

这是一个演示。单击“添加项目”按钮,您将看到列表由于重复上的一次性绑定而刷新。检查刷新值并再次单击,项目将更新:

&#13;
&#13;
var app = angular.module('demo', []);

app.controller('RefreshCtrl', function($scope, $timeout) {
  var counter = 4;

  $scope.visible = true;

  $scope.items = ['Item1', 'Item2', 'Item3'];

  $scope.addItem = function() {

    if ($scope.refresh) {
      $scope.visible = false;
    }

    $scope.items.push('Item' + counter);

    counter++;

    $timeout(function() {
      $scope.visible = true;
    });
  };

});
&#13;
<script src="https://code.angularjs.org/1.3.17/angular.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

<div ng-app="demo" ng-controller="RefreshCtrl" class="container">
  <button class="btn btn-default" ng-click="addItem()">Add Item</button>
  <input type="checkbox" ng-model="refresh" />Refresh Values
  <div ng-if="visible">
    <h3 ng-repeat="item in ::items">{{item}}</h3>
  </div>

  <p>Items Array: {{items}}</p>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:5)

根据您的目标,我建议采用以下两种解决方案之一:

我是前者的作者,它与其他解决方案的最大区别在于可以选择挂钩$parse服务。

因此,您可以在Angular的大多数(如果不是全部)区域中使用引入的{{:refreshkey:expression}} / :refreshkey:expression语法,其中接受表达式。

在您的情况下,实现可能如下所示:

<强> JS

angular.module('app', []).controller('AppCtrl', function($scope) {
  $scope.items = [
      {id: 1},
      {id: 2},
      {id: 3}
  ];

  $scope.addAndRefresh = function() {
      $scope.items.push({id: 4});
      /**
       * '$$rebind' is the internal namespace used by angular-bind-notifier.
       * 'refresh' is the refresh key used in your view.
       */
      $scope.$broadcast('$$rebind:refresh');
  };
});

<强>标记

<!-- HTML template -->
<div ng-repeat="item in :refresh:items">
    {{::item.id}}
</div>
<button ng-click="addAndRefresh()">Add</button>

或者,如果你想要一些半动态的东西

<强> JS

angular.module('app', []).controller('AppCtrl', function($scope) {
  $scope.items = [
      {id: 1},
      {id: 2},
      {id: 3}
  ];

  $scope.add = function() {
      $scope.items.push({id: 4});
  };
});

<强>标记

<!-- HTML template -->
<div bind-notifier="{ refresh: items.length }">
  <div ng-repeat="item in :refresh:items">
      {{::item.id}}
  </div>
</div>
<button ng-click="add()">Add</button>

查看README和此jsBin以获取一些使用示例。

相关问题