AngularJS - 将值从后端传递到前端

时间:2012-11-24 13:54:57

标签: angularjs

在前端将值从后端传递给AngularJS的最佳方法是什么?我正在使用Django,模板能够吐出我需要的值,但是我不确定将这些值传递给AngularJS的最佳做法是什么。

想想一篇博客文章及其评论,如果我有一个AngularJS服务,它通过将帖子ID传递给服务来检索某篇博文的所有评论,而Django正在呈现HTML模板,它确实知道什么是帖子ID,但我需要将此帖子ID传递给AngularJS,然后传递给服务。

一个想法是将其置于隐藏的<input>中并将此输入分配给模型。不太吸引人。

另一个是有一个指令并将一个属性中的这个值传递给这个指令,这样我就可以访问这个属性的值了:

// Django (or any backend) is rendering {{ object.value }}
<div class="myDirective" data-object-id={{ object.value }}>
   ...
</div>

angular.module('myDirectives', []).
    directive('myDirective', function() {
        return {
            restrict: 'C',
            transclude: false,
            link: function postLink($scope, $element, $attrs) {
                // $attrs.objectId would have the value
            }
        }
    });

这两种方法看起来很好。但我想知道是否有更清洁的方法这样做?遵循AngularJS最佳实践的任何方法?

3 个答案:

答案 0 :(得分:22)

如果您只需要从视图中初始化少数模型值,那么ng-init指令可能就是您要查找的内容:http://docs.angularjs.org/api/ng.directive:ngInit

使用它你只需写:

<div ng-init="myModel=backend-generated-value-here">
   ...
</div>

说完上述内容后,您可能会有一些困难时间为您的用例找到最佳实践,因为AngularJS专注于Web2.0,全客户端Web应用程序。目前,它无法与服务器端生成内容理想地发挥作用。它可能会在AngularJS的未来版本中发生变化。

答案 1 :(得分:9)

如果您只需要为给定的“页面”设置初始值(意味着对视图的后端调用),那么您可以按照演示进行操作。我只会通过javascript设置一个全局变量来使它“更清洁”,如下所示:

// Django (or any backend) is rendering {{ object.value }}
<script>
  var backendVars = {
    {{object.name}} : {{object.value}}
    //and any other objects, manually parsed
  }
</script>

在自举过程中用角度读取它。

但是,angularJS是它自己的MVC,因此您可能希望能够设置/获取数据或后端控制器的进程,而无需重新加载整个页面。然后,“最干净”的方法是使Web服务返回您需要的数据(例如,返回JSON的视图)并通过$ http或$ resource服务检索它:

angular.module('myApp', []).
  controller('MainCtrl', function($scope, $html) {
    $html({
    method: 'GET',
    url: '/your/JSON/view.json'
      }).
      success(function(data, status){
        $scope.yourData = data;
      }).
      error(function(data, status){
        //whatever you need to do if the data is not available
      });
  }

另外,我应该注意,你不应该直接将数据和逻辑放在指令上 - 它们用于DOM操作 - 而是在控制器上获取信息,然后通过范围继承,属性或者将它传递给指令。双向数据绑定。希望它有所帮助。

答案 2 :(得分:9)

我认为正确的方法是让服务器使用value provider呈现脚本,然后在应用中依赖注入它。像这样:

的index.php:

<html ng-app='myApp'>

<head>
    <title>AngularJS Back to Front</title>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js"></script>
    <script src='index.js'></script>
    <?php
        $globals = array(
            'count' => 1, 
            'title' => 'Active users',
            'users' => array(
                'name' => 'john',
                'age'  => 21
            )
        );

        $globalsJSON = json_encode( $globals )
    ?>

    <script>
        myApp.value('globals', <?=$globalsJSON;?>);
    </script>
</head>

<body ng-controller="myController">
    <div>{{title}}</div>
</body>

</html>

index.js:

var myApp = angular.module( 'myApp', [] );

myApp.controller( 'myController', [ 'globals', '$scope', function( globals, $scope ) {
    // Copy globals to scope
    for ( var property in globals ) {
        $scope[ property ] = globals[ property ];
    }
}]);
相关问题