Running PHP within angular

后端 未结 1 1213
清酒与你
清酒与你 2020-12-20 06:52

I am using angular to create page transitions in a wordpress site. My site loads a normal wordpress page which fires its PHP and populates the page with angular elements (th

相关标签:
1条回答
  • 2020-12-20 07:27

    AngularJS is completely client side. You can put PHP in your HTML templates, but if you don't configure your webserver to parse HTML files as PHP then your PHP isn't even going to be parsed.

    Even if it did, AngularJS caches these templates so it will only be 'run' on the server a single time. This means if the template in question is swapped out, then data changes on the server that the template makes use of and then it is swapped back in again, the updates to the data are not going to be reflected in the template because there's absolutely zero knowledge on Angular's side of these updates occurring.

    A good idea like @Jonast92 says in his comment is to try not to mix client-side and server-side concerns and enforce a strict separation between them. Use Angular models in your angular application's templates. Instead of something like:

    <p><?php echo $item->description; ?></p>
    

    Use an angular model:

    <p>{{ item.description }}</p>
    

    If you need data from the server in order to do this, make an Angular service to go out and get it for you:

    angular.module('app').controller('controller', [
        '$scope', 'ItemManager',
        function($scope, ItemManager) {
            $scope.item = null;
    
            ItemManager.getItem('item-id').then(
                function(item)  {
                    $scope.item = item;
                }, function() {
                    console.log('load item failed');
                }
            );
        }
    ]);
    
    angular.module('app').service('ItemManager', [
        '$http', '$q',
        function($http, $q) {
            var svc = {
                getItem: getItem
            };
    
            return svc;
    
            function getItem(id) {
                 var defer = $q.defer();
                 $http.get('/items/' + id)
                     .success(function(data) {
                         defer.resolve(data);
                     })
                     .error(function() {
                         defer.reject();
                     })
                 ;
    
                 return defer.promise;
            }
        }
    ]);
    
    0 讨论(0)
提交回复
热议问题