简体   繁体   English

从HTML标签初始化AngularJS模型

[英]Initialize AngularJS Model From HTML Tag

I'm working with django + angular. 我正在使用Django + angular。 I'd like django to populate a value in the HTML template, and then tell Angular to use that value as initial value for a model. 我希望django在HTML模板中填充一个值,然后告诉Angular使用该值作为模型的初始值。

I need this for two reasons: 我有两个原因需要它:

  1. Simplicity - The page deos not currently use Angular, and I believe it would be easier to upgrade this way. 简便 -页面Deos当前不使用Angular,我相信通过这种方式升级会更容易。
  2. SEO - Some search engines can't read values populated in the DOM through Angular. SEO-某些搜索引擎无法通过Angular读取DOM中填充的值。 I know there are several solutions for SEO with Angular but I hope there's an easier way? 我知道有几种针对Angular的SEO解决方案,但我希望有一种更简单的方法?

Any help would be greatly appreciated :) 任何帮助将不胜感激 :)

You can initialize you model based on that initial HTMl value. 您可以基于该初始HTM1值初始化模型。

For instance your HTML would be: 例如,您的HTML将是:

<div ng-bind="value">initialValue</div>

And you controller: 而您的控制器:

var elem = $( 'get the element' );
$scope.value = elem.text();

Angular will then take over and can reflect any change made to $scope.value . 然后,Angular将接管并可以反映对$scope.value所做的任何更改。

The downside is that you need to grab the element (using jQuery here for simplicity but you can use vanilla Javascript). 缺点是您需要获取元素(为简单起见,在此处使用jQuery,但可以使用原始Javascript)。

One way to work around that would be a custom directive: 解决该问题的一种方法是自定义指令:

<div late-binding="value">initialValue</div>

I let the directive code as an exercice to the reader, unless you need help for it :) 我让指令代码作为读者的练习,除非您需要帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM