【问题标题】:How to redirect to another page on ng-click using angularjs or coffeescript?如何使用angularjs或coffeescript在ng-click上重定向到另一个页面?
【发布时间】:2015-12-14 18:18:11
【问题描述】:

我现在在 angularjs 和 coffeescript 中做一些任务。我有这样的要求:我的 html 页面中有几个按钮,例如:

<div>
    <button type="button" class="btn btn-default" ng-click="button1();">Button1</button>
    <button type="button" class="btn btn-default" ng-click="button2();">Button2</button>
</div>

如果我点击 Button1,那么它应该重定向到另一个页面(比如:'/test1.html'),同样,如果我点击 Button2,那么它应该重定向到另一个页面(比如:'/test2.html ')。 如何在 AngularJS/CoffeeScript 中做到这一点?

如果我在我的咖啡脚本文件中这样做,我会收到以下错误:

app = angular.module('myApp', dependencies)
app.controller 'WizardController', [
  '$scope',
  ($scope) ->
  $scope.button1 = ->
    window.location = '/test1.html'
    return

    $scope.button2 = ->
    window.location = '/test2.html'
    return
  ]

但它在返回语句处给出编译错误:编译错误:第 103 行的解析错误:意外的 'TERMINATOR'

【问题讨论】:

    标签: javascript html angularjs coffeescript


    【解决方案1】:

    您可以直接从您的 HTML 页面重定向:

    <div>
      <button type="button" class="btn btn-default" ng-href="/test1.html">Button1</button>
      <button type="button" class="btn btn-default" ng-href="/test1.html">Button2</button>
    </div>
    

    或者在你的代码中你应该删除';'从

    ng-点击

    如:

    <div>
      <button type="button" class="btn btn-default" ng-click="button1()">Button1</button>
      <button type="button" class="btn btn-default" ng-click="button2()">Button2</button>
    </div>
    

    我还会检查您的咖啡脚本中的缩进,因为它往往有点模糊。

    app = angular.module('myApp', dependencies)
    app.controller 'WizardController', [ '$scope', '$location',
    ($scope, $location) ->
      $scope.button1 = ->
        $location.path('/test1.html')
    
      $scope.button2 = ->
        $location.path('/test2.html')
    ]
    

    【讨论】:

    • ng-href 是一个很好的解决方案,但需要注意:使用 angular 时不要使用 window.location,只需使用 $location。
    • 大家好,谢谢大家,我已经完成了上面的操作,但我仍然收到错误(在 $location.path 行):第 218 行的解析错误:意外的 'INDENT' 并​​且如果添加 ng-href ,它也不起作用。
    • 正如我在帖子中所说,缩进在coffeescript中非常重要。检查我编辑的 js 文件,也在你的文件中,选择所有然后将缩进转换为空格。
    • 缩进错误现在已解决,但如果我使用上面的代码,我仍然无法重定向到另一个页面
    • 错误是:未捕获错误:未知提供者:来自 myApp 的 $controllerProvider 并且 $scope 未定义
    猜你喜欢
    • 2019-09-19
    • 2014-10-17
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    相关资源
    最近更新 更多