Angularjs: server side (php) rendering and data binding client side after an event

流过昼夜 提交于 2019-12-04 08:18:26

isomorphism

I wanted to know if there is a better one or maybe another js framework that does exactly what I'm trying to do

You are trying to build an isomorphic application. React will allow you to create isomorphic applications, but normally requires the backend be built in node.js. There is a way to use React with PHP. There are other solutions to isomorphism as well.

binding

the important thing is for angularjs to not rewrite what server side has already been writen(redered)

You can feed angular the server-side data by passing it in the HTML with a script tag, using the json_encode PHP function. This way angular will have the correct data when it starts up.

 <script>
  angular.module('app').constant('applicationData', <?= json_encode(application_data) ?>);
 </script>

Then you can inject applicationData and use it to initialize your directive. This approach is less than ideal because it forces you to deal with the same data twice. That's why using a view library like React which was built to support isomorphism is probably a better choice when creating an isomorphic application.

The Text: hola server side inside the Tag is useless, because it is replaced by Angular with the Content of Greeting. The Content of Greeting ist empty at start of the app.

Initialized of greeting in javascript

var myApp = angular.module('myApp',[]);
myApp.controller('GreetingController', ['$scope', function($scope) {
    $scope.greeting = "greeting initialized";
    $scope.update = function (){
          //do ajax calls and set greeting and other data to bind
        $scope.greeting = 'Hola!';
    }
}]);

complete example http://jsfiddle.net/ud6z4krk/5/

or

Initialize in greeting in HTML with ng-init

<div ng-app="myApp">
<div ng-controller="GreetingController">
  <span ng-init="greeting = 'hola server side'" ng-bind="greeting"></span>
  <button ng-click="update()">update</button>
</div>
</div>

complete example http://jsfiddle.net/ud6z4krk/8/

Or you make a new attribute-directive for your update-button. In the parameters of the directive you can reference to your content-tag. The directive add an Event to the update button to get the new Data from the server and update the contents of the referenced tag.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!