Is there a way to get AngularJS to work with HTML first?

Is there a way to have an HTML view with pre-populated values ​​from the server and then get AngularJS to read these values ​​in it $scope ?

I am thinking of a scenario where the HTML looks like this:

 <div ng-controller="TestController"> <div ng-bind="title">Test Title</div> <div ng-bind="itemCount">33</div> <div ng-repeat="item in items"> <div ng-bind="item.title">Item 1 Title</div> </div> </div> <button ng-click="update()">Update</button> 

And JavaScript looks like this:

 function TestController($scope) { $scope.update = function() { console.log($scope.title); // Should log "Test Title" }; } 

The idea is to allow the server to render HTML, which search engines can index , but have a version of the JavaScript model for the strong> model for manipulation via JS.

+8
angularjs seo
source share
3 answers

While ng-init is one solution, this requires explicitly setting the value. So here is an alternative solution.

http://plnkr.co/edit/pq8yR9zVOHFI6IRU3Pvn?p=preview

Note This solution will not work for ng-repeat . You cannot use flow control directives. But for simple retrieval of information from ng-bind this works very well. All you have to do is add the default directive (the code in plunk) to where you are binding, and will extract the text content and click on the scope variable.

EDIT (solution with ng-repeat):

So, I was thinking of a way to make ng-repeat work the same way. But getting ng-repeat to work as if it is not an easy task (see Code for proof: P). I finally found a solution - here you go:

http://plnkr.co/edit/GEWhCNVMeNVaq9JA2Xm2?p=preview

There are a few things you need to know before using this. This has not been thoroughly verified. It only works for repeating arrays (not objects). There may be cases that were not covered. I overestimate ngRepeat itself, which may have other consequences. When you iterate over elements (in the server-side code), remember to add default="true" to the first element and default to the rest of the elements.

Hope this helps.

+7
source share

Add ng-init to your elements with a value so that it works the way you want.

http://docs.angularjs.org/api/ng.directive:ngInit

0
source share

I think that you really want your application to be searchable by providing static files in parallel. More on this here http://www.yearofmoo.com/2012/11/angularjs-and-seo.html

0
source share

All Articles