One time binding: update model and re-render view

后端 未结 2 2016
庸人自扰
庸人自扰 2020-12-31 07:59

I was wondering if possible, using angular one time binding, to completely re-render the view/template after a model update, also by recompiling the template. For instance,

2条回答
  •  难免孤独
    2020-12-31 08:24

    Depending on what you are after, I would recommend one of two solutions:

    • Get angular-bind-notifier.
      • Does not recompile your template, only refreshes the bound values.
    • Get kcd-recompile.
      • Recompiles the template along with the bound values.

    I'm the author of the former, and the big difference between it and other solutions is the choice of hooking into the $parse service.

    As such, you can use the introduced {{:refreshkey:expression}}/:refreshkey:expression syntax in most (if not all) areas of Angular where an expression is accepted.


    In your case, the implementation could look something like this:

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

    markup

    
    
    {{::item.id}}

    Or, if you wanted something semi-dynamic

    js

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

    markup

    
    
    {{::item.id}}

    Check out the README and this jsBin for some usage examples.

提交回复
热议问题