本文介绍了AngularJS - 获取插入 dom 中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在应用程序加载后从 DOM 获取初始数据的方法.数据已由服务器插入到视图中.Modulevalue 方法是不是好方法?

I'm looking for a way to get initial data from a DOM after the application is loaded. Data has been inserted in a view by a server. Is Module's value method is a good way?

我还想知道在使用 routes 时如何从视图中获取数据,我可以使用 script 标签在特定范围内注入数据吗??

As well i want to know how to get data from a views when i'm working with routes , can i use script tags for injecting a data in specific scopes?

我看到了这个这个 问题,但它没有多大帮助.

I saw this and this questions but it didn't help a lot.

推荐答案

1) 受 这个问题,它是Modulevalue 方法:

1) First solution inspired by this question and it is Module's value method:

<script>
   var users_json = '[{"name":"Piotr"},{"name":"Natasha"}]'; // created by xsl
   myApp.value("PrimaryData" , users_json );
</script>
<ul>
   <li ng-repeat="user in users">{{user.name}}</li>
</ul>

然后我们可以在我们希望的时间和地点使用这个PrimaryData,就像这样:

Then we can use this PrimaryData when and where we wish , like this:

myApp.controller('MainCtrl', function($scope, PrimaryData) {
    $scope.data = angular.copy(PrimaryData);
    console.log( $scope.data[0].name === "John" );
});

但是当我开始使用 routes 时,这种方式对我不起作用,可能是因为 value 仅在应用程序初始化时运行.

But this way somehow not worked for me when i started to use routes , may be because the value only runs while application initialization.

2) 所以这里是第二个解决方案:指令.现在,当服务器发送路由的模板时,它会在一些 script 标签中放入一个 "text/template" 类型和特殊指令名称属性以及该标签中的 json 数据,例如这个:

2) So here comes the second solution: directives. Now when server sends a route's template , it puts inside some script tag with a "text/template" type and special directive name property and a json data in that tag, like this:

<script  type = "text/template" rawdata >     <!-- "rawdata" is our directive
   '[{"name":"Nelson"},{"name":"Luis"}]'      // created by xsl
</script>
<ul>
   <li ng-repeat="user in users">{{user.name}}</li>    // view is beside
</ul>

这个指令捕获它并将数据传递到当前路由的作用域:

And this directive catching it and passes the data to the current route' scope:

studio.directive('rawdata', function() {
  return {
    link: function(scope, element, attr, ctrl) {
        if(scope.passRawData){
            var data = (element[0].innerHTML);
            scope.passRawData(data); // Or simply scope.users = JSON.parse(data)
        } else {
            console.log( "Scope has no passRawData method" );
        }
    }
  }
});

太棒了!:)

这篇关于AngularJS - 获取插入 dom 中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 08:58
查看更多