Add another custom interpolator in Angularjs

不打扰是莪最后的温柔 提交于 2019-12-12 01:06:53

问题


I still want {{1+2}} to be evaluated as normal. But in addition to the normal interpolator, I want to create a custom one that I can program to do whatever I want.

e.g. <p>[[welcome_message]]</p> should be a shortcut for <p>{{'welcome_message' | translate}}</p>, or <p translate="welcome_message"></p>. That way, i18n apps would be much more convenient to write.

Is anything like that possible? I'm currently going through the angular.js source code, but the interpolation system looks pretty complicated(?). Any suggestions?


回答1:


I created a directive that regex-find-replaces it's innerHTML. Basically, I can rewrite any text into any other text. Here's how I did it:

How do I make angular.js reevaluate / recompile inner html?

Now all I have to do is to place my directive-attribute, "autotranslate", in one of the parent elements of where I want my interpolator to work, and it rewrites it however I want it! :D

<div class="panel panel-default" autotranslate>
  <div class="panel-heading">[[WELCOME]]</div>
  <div class="panel-body">
    [[HELLO_WORLD]
  </div>
</div>

becomes

<div class="panel panel-default" autotranslate>
  <div class="panel-heading"><span translate="WELCOME"></span></div>
  <div class="panel-body">
    <span translate="HELLO_WORLD"></span>
  </div>
</div>

which does exactly what I wanted.




回答2:


I don't think that's possible, but if you really want to save some characters you could create a function on your rootScope called t, then call it within your views:

<p>{{ t(welcome_message) }}</p>


来源:https://stackoverflow.com/questions/21483857/add-another-custom-interpolator-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!