是否有可能提供转换对象转换成字符串角模板的含蓄的方式? [英] Is it possible to provide an implicit way of converting object into string for angular templates?

查看:95
本文介绍了是否有可能提供转换对象转换成字符串角模板的含蓄的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我有一个具有相同的原型几个对象,我想自定义其显示在角模板。我知道我可以创建自己的过滤器,然后用它这样的:

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 it like that:

<p>{{anObjectOfProtoP | myCustomFilter}}</p>

或连接到$范围的函数:

or a function attached to $scope:

<p>{{myCustomFunction(anotherObjectOfProtoP)}}</p>

我的问题是:是否有可能没有明确指定每次渲染功能来实现类似的功能?理想的解决方案是,如果角度检查功能 toAngularString 里面的 {{}} ,然后用它的对象模板返回值。
换句话说,我想角做

My question is: is it possible to achieve similar functionality without explicitly specifying the rendering function every time? The ideal solution would be if angular checked for function toAngularString on object inside the {{}}, and then used it's return value in template. In other words, I'd like Angular to do

function (o) {
   if (typeof o.toAngularString === 'function') return o.toAngularString();
   return o;
}

每个对象{{}}

推荐答案

根据是否使用 {{...}} 纳克-bind 语法中, .toJSON 和你的对象上的的ToString 功能将调用,以确定其重新presentation。因此,你可以提供你想要的重presentation无论是的ToString .toJSON 你的对象的功能。

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.

你可以做的另一种方式是通过编写自己的指令我-toangularstr 就象这样:

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

显示所有三种方法工作演示是这里

我认为这是接近人能获得使用角度外部API。

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

这篇关于是否有可能提供转换对象转换成字符串角模板的含蓄的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆