Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

javascript - AngularJS - Getting data inserted in dom

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?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

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

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

Awesome! :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...