在钢轨路线AngularJS参数 [英] Rails Route parameters in AngularJS

查看:125
本文介绍了在钢轨路线AngularJS参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图建立一个AngularJS / Rails的多页的应用程序,而无需使用ngView-基本上,我想用角的数据绑定,在我的滑轨其他功能的应用程序,同时还具有用我的Rails的路线决定的意见。到目前为止,它是工作好了,但我的主要问题已经从我的角度范围内访问我的滑轨路线参数。是否有访问的角度友好的方式URL /参数的方法吗?我不想再打了切片window.location的。

I am trying to build an AngularJS/Rails multi-page app WITHOUT the use of ngView- basically, I want to use Angular's data-binding and other features in my rails app while still having the views determined by my Rails routes. So far, it is working alright, but my main problem has been accessing my rails routes parameters from within my Angular framework. Is there a way to access the URL/parameters in an Angular-friendly way? I don't want to resort to slicing up window.location.

举例来说,可以说我在本地主机:3000 /用品/ 1,我的观点会相应的应用程​​序/视图/条/ show.html.erb

For example, lets say I'm in localhost:3000/articles/1, with my view would corresponding to app/views/article/show.html.erb

<div class='articleContainer' ng-controller='ArticleController'>
  <div class='articleTitle' ng-bind='article.title'></div>
  <div class='articleBody' ng-bind='article.body'></div>
</div>

这是我的ArticleController会是什么样子在传统的角度设置。

This is what my ArticleController would look like in a traditional Angular setup.

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

ArticlesControllers.controller('ArticleController', ['$scope', '$routeParams',"$http","$browser","$sniffer","$rootElement", "$location",
  function($scope, $location, $http, $resource){
    $http.get('/articles/'+$routeParams.articleId+'.json').success(function(data) {
      $scope.article = data["article"];
      $scope.comments = data["comments"];
    });

  }
]);

不幸的是,$ routeParams似乎没有,如果我不使用ngView工作。有没有干净的方式来重新创建$ routeParams.articleId而不诉诸window.location的?衷心感谢你。

Unfortunately, $routeParams does not seem to work if I am not using an ngView. Is there a clean way to recreate $routeParams.articleId without resorting to window.location? Thank you kindly.

推荐答案

在嵌入的articleContainer DIV的数据元素,像这样的文章编号:

Embed the article id in a data element on the articleContainer div, like so:

<div class='articleContainer' ng-controller='ArticleController' id='articleContainer' data-article-id=<% =@article.id.to_s %> >
  <div class='articleTitle' ng-bind='article.title'></div>
  <div class='articleBody' ng-bind='article.body'></div>
</div>

我添加了一个id到div为通过JavaScript参考。

I added an id to the div for easy reference via javascript.

然后,在你的JavaScript检索数据元素,当你需要它:

Then, in your javascript retrieve that data element when you need it:

(假定的jQuery)

(assumes jQuery)

var articleId = $('#articleContainer').data('article-id');

这篇关于在钢轨路线AngularJS参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆