Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to make AngularJS work with HTML-first?

Tags:

angularjs

seo

Is there a way to have a HTML-view with pre-populated values from the server, and then get AngularJS to read those values into it's $scope?

I'm thinking of a scenario where the HTML is 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 the JavaScript is like this:

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

The thought behind this is to let the server render HTML that search engines can index, but have a JavaScript-model-representation of the content for manipulation through JS.

like image 747
Seb Nilsson Avatar asked Apr 05 '13 13:04

Seb Nilsson


1 Answers

While ng-init is one solution, it requires you to explicitly set the value. So here is an alternative solution.

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

Note : This solution wont work for ng-repeat. Control flow directives cant be used with this. But for simple extraction of information from ng-bind this works pretty well. All that you need to do is add the default directive ( code in plunk ) to wherever you are doing the bind and it will extract the text content and push it to the scope variable.

EDIT (solution with ng-repeat):

So, I was thinking of a way to make ng-repeat also work the same way. But getting ng-repeat to work like this isnt an easy job ( see the code for proof :P ). I have finally found a solution - here you go :

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

There are a couple of things you need to know before you use this. This hasnt been thoroughly tested. It only works for repeating over arrays ( not objects ). There could be cases that have not been covered. I am overriding ngRepeat itself which could have other consequences. When you loop through the items ( in your server side code ) dont forget to add default="true" on the first element and default on the rest of the elements.

Hope this helps.

like image 184
ganaraj Avatar answered Sep 23 '22 20:09

ganaraj