Angular JS中视图的访问ID

Access ID of view in Angular JS

本文关键字:访问 ID 视图 JS Angular      更新时间:2023-09-26

加载视图后,如何访问控制器中客户的customerId

app.js:

  $stateProvider.state('app.customer', {
    url: '/customer/:customerId',
    views: {
      'menuContent': {
        templateUrl: 'templates/customer.html',
        controller: 'CustomerCtrl'
      }
    }
  })

customers.html:

<a class="item item-points" ng-repeat="customer in customers" href="#/app/customer/{{customer.Customer.id}}"> ...

在控制器中注入$stateParams服务

angular
  .module('yourmodule')
   .controller('CustomerCtrl',['$scope','$stateParams', function($scope, $stateParams){
     console.log($stateParams); //should be object {customerId: 'id-of-customer'}
  }])

您可以从$stateParams在控制器中获得它,只需要在控制器中添加$stateParams依赖项。基本上$stateParams将具有URL(在对象中)中的所有参数

$stateParams.customerId; //

我还建议您使用ui-sref指令,而不是自己创建URL,这将通过查看状态来创建具有正确URL的href。

<a class="item item-points" 
   ng-repeat="customer in customers" 
   ui-sref="app.customer({customerId : customer.Customer.id})">
  ...
</a>

在控制器中。。。

$stateParams.customerId (injecting $stateParams service)

$state.params.customerId (injecting $state service)

我更喜欢第二种方法,因为我使用$state.go等,所以只使用这个

更容易