【问题标题】:how to load angular $scope data into a location.href?如何将角度 $scope 数据加载到 location.href 中?
【发布时间】:2016-03-26 09:00:34
【问题描述】:

我有以下

    <div>
        <div ng-repeat="data in datas" title='{{ data.name }}' onClick="location.href='\{{ data.name }}'" >{{ data.name }}</div><br/>
    </div>

在我的角度文件中

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

 mainApp.controller('formCTR',['$scope','$http',function($scope,$http){
   $http.post('/here',{ data: 'something' }).success(
       function(data){
          $scope.datas=data;
       }
   )
  }]);

当我点击 url 时显示

http://localhost:3000/url/{{ data.name }}

如何在 onClick to 中显示数据的名称

http://localhost:3000/url/right_name

谢谢

【问题讨论】:

  • 您是否尝试过使用 ng-click。 this stack overflow question, or this one
  • 感谢@guest 的帮助,但对我没有用。
  • @luis var 或 $scope 变量的数据范围是什么,如果是范围变量,那么您的 $http 配置和 html 页面范围是相同还是不同?请提供带有控制器和 html 的小提琴或代码,以便我们了解您的 prgram 的范围
  • 使用jsfiddle.net

标签: angularjs


【解决方案1】:

如果您想以 Angular 进行重定向,您可以使用使用点击处理程序的“ng-click”或带有如下网址的“ng-href”的 2 个步骤中的任何一个:

<div>
<div ng-repeat="data in datas" title='{{ data.name }}' ng-click="redirect(data.name)" >{{ data.name }}</div><br/>
</div>

并在您的控制器范围内添加 redirect 函数

$scope.redirect = function (route) {
  $location.path('/' + route);
}

这种方法允许您通过更改参数使用相同的功能重定向到多个路由。

如果您只需要使用ng-href 指令进行重定向,则第二种方法是一种简单而优雅的方法:

<div>
  <div ng-repeat="data in datas" title='{{ data.name }}'>
    <a ng-href="/{{ data.name }}">{{ data.name }}</a>
  </div><br/>
</div>

【讨论】:

    【解决方案2】:

    使用ng-click 而不是onClick...

    控制器

    ...
    $scope.redirect = function(route) {
       $location.path('/' + route);
    }
    ...
    

    模板

    <div>
        <div ng-repeat="data in datas" title='{{ data.name }}' ng-click="redirect({{ data.name }})" >{{ data.name }}</div><br/>
    </div>
    

    ...或使用锚标记和ng-href。

    <div>
        <div ng-repeat="data in datas" title="{{ data.name }}"><a ng-href="\{{ data.name }}">{{ data.name }}</a></div><br/>
    </div>
    

    【讨论】:

    • ng-click 不知道location 是什么...它不在控制器范围内...它是一个全局窗口
    • 谢谢@hally9k,第二个成功了!希望第一个也能成功,这样我就不必为a标签写另一个css了。
    • 不,第一个不会起作用,除非并且直到您在 $scope 对象上公开 $location 服务。您只能访问 $scope 对象上添加(公开)的属性。一般来说,这不是一个好习惯。详情见我的回答
    • @hally9k 查看您的代码后,您不需要在双引号后的ng-href 内加单引号
    猜你喜欢
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多