【问题标题】:how to pass global variable in view to controller angularjs如何将视图中的全局变量传递给控制器​​angularjs
【发布时间】:2015-01-21 21:56:24
【问题描述】:

我正在尝试通过 ejs 将后端发送到前端,angularjs 的控制器

app.js
我将数据传递给视图/索引内容。

var users = [
  {
    name: 'john',
    email: 'john@email.com'
  },
  {
    name: 'peter',
    email: 'peter@email.com'
  },
  {
    name: 'max',
    email: 'max@email.com'
  }
];

app.get('/partials/indexContents.html', function(req, res) {
  res.render('partials/indexContents', {users:users})
});
app.get('/partials/about.html', function(req, res) {
  res.render('partials/about')
});

视图/部分/索引内容
我把它设为全局变量。

  <div>
    <h3>home</h3>
    <p>wecome to my blog. I hope you enjoy the content!</p>
    <ul>
        <li ng-repeat="post in blogposts">{{post}}</li>
    </ul>
  </div>
        <script>
             users = "<%=abc=users[0].name%>";
        </script>

public/js/contollers.js
试图获取全局变量

var app= angular.module('blog',['ngRoute']);

app.config(function($routeProvider) {
    //set up routes
    $routeProvider
    .when('/home',{
        templateUrl:'partials/indexContents.html',
        controller:'SimpleController'
    })
    .when('/about',{
        templateUrl:'partials/about.html',
        controller:'AboutController'
    })      
    .otherwise({
        redirectTo:'/'
    });
});


app.controller('SimpleController', function($scope){

    $scope.blogposts=[
    'blog post1',
    'blog post2',
    window.users
    ];
}); 


app.controller('AboutController', function($scope){
    $scope.name="graum";
    $scope.bio="i just made it";
});

但它只显示空白而不是“约翰”。

请给我一个解决方案,谢谢

【问题讨论】:

  • 您是否有兴趣将数据封装在服务中?
  • @user3713746 看看我的回答

标签: angularjs express ejs


【解决方案1】:

为什么不使用 $resource 从服务器获取名称?我知道这不是最好的选择,当然也不是你要找的,但这样肯定会奏效。 不过你也可以试试这个

<script>
         (function() {users = "<% users[0].name%>";})();
</script>

【讨论】:

    猜你喜欢
    • 2019-06-02
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    相关资源
    最近更新 更多