Is it possible to provide an implicit way of converting object into string for angular templates?

前端 未结 1 1097
天命终不由人
天命终不由人 2021-01-06 18:29

Let\'s assume I\'ve got a few objects that have the same prototype and I want to customize their display in Angular template. I know I can create my own filter, and then use

相关标签:
1条回答
  • 2021-01-06 18:43

    Depending on whether you use {{ ... }} or ng-bind syntax, the .toJSON and the .toString function on your object will be called to determine its representation. Hence, you can provide the representation you want in either .toString or .toJSON function of your object.

    This discrepancy in which function is called has let to some problems, actually.

    Another way you can do that is by writing your own directive my-toangularstr as this:

    app.directive('myToangularstr', function () {
      return {
        scope: true,
        template: '<span class="my-angular-value">{{ val.toAngularString() }}</span>',
        link: function (scope, elem, attrs) {
          scope.$watch(attrs['myToangularstr'], function (newVal) {
            if (typeof newVal !== 'undefined') {
              scope.val = newVal;
            }
          })
        }
      }
    })
    

    A working demo showing all three methods is here.

    I think that is as close as one can get using the external API of angular.

    0 讨论(0)
提交回复
热议问题