【问题标题】:angularjs routing error inside a controller控制器内的angularjs路由错误
【发布时间】:2015-02-10 00:18:37
【问题描述】:

我有以下angularjs 路由设置。

app.js

.config(function($stateProvider, $urlRouterProvider){
  //some code
  .state('app.edit', {
    url: '/edit/:recipeId',
    views: {
      'menuContent': {
        templateUrl: 'templates/recipes/edit.html',
        controller: 'editRecipeCtrl'
      }
    }
  //some code
});
$urlRouterProvider.otherwise('/app/home'); 

查看

<a ng-click="editDemo()" href='#'>Edit</a>

问题是当我点击链接时,它没有进入编辑页面。 (以下是观察结果)

  • 控制台没有错误
  • 我可以看到地址栏中的 url 正在改变,但它很快 返回首页
  • 如果我在地址栏中输入http://localhost/#/app/edit/1,它会起作用
  • 它调用editDemo() 方法。

controller.js

$scope.editDemo = function(){
    // options I tried
     
    // $location.path( '/edit/1' );
    // $location.path( '#/app/edit/1');  
    // $location.path( 'edit/1');  
    // $location.url( '/edit/1' );
    // $location.url( '#/app/edit/1' ); 
    // $location.url( 'edit/1');
    // location.href = '/#/app/edit/1';
}

任何帮助将不胜感激。

【问题讨论】:

  • $location.path( '/edit/1' ); 应该是正确的,尝试将$event 传递给ng-click 回调并调用$event.preventDefault()
  • @Rasalom,感谢您的快速回答,我将链接更新为 div &lt;div ng-click="editDemo()"&gt;Edit&lt;/div&gt; 并将代码更新为 $location.path( '/edit/1' );,但仍然无法正常工作

标签: angularjs ionic-framework angularjs-routing


【解决方案1】:

我更喜欢(以防止陷入困境)使用 $state 服务

$scope.editDemo = function(id) {
    $state.go('app.edit', {recipeId: id});
}

【讨论】:

    【解决方案2】:

    您至少有两种方法:

    1) 从&lt;a&gt; 标签中删除href&lt;a ng-click="editDemo()"&gt;Edit&lt;/a&gt; 并在editDemo中:

    $scope.editDemo = function(){
       $location.path( '/edit/1' );
    }
    

    2) 在editDemo中处理点击事件:

    <a ng-click="editDemo($event)" href='#'>Edit</a>
    
    $scope.editDemo = function($event){
         $event.preventDefault();
         $location.path( '/edit/1' );
    }
    

    【讨论】:

    • 感谢@Rasalom,我将代码更改为 Ben 的方式,现在可以正常工作了。我相信它更像angular。但再次感谢:)
    猜你喜欢
    • 2015-09-26
    • 2013-04-22
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多