【问题标题】:Why am I unable to access $stateParams on controller ng-init?为什么我无法访问控制器 ng-init 上的 $stateParams?
【发布时间】:2016-10-20 14:15:02
【问题描述】:

我在 body 标记中使用控制器来实例化一些通过应用程序使用的变量,即将在应用程序中使用的语言(基于 url 参数)。

<!--index.html-->
<body ng-controller="AppCtrl" ng-init="init()">
    <section ui-view></section>
</body>

在 init() 函数中,我尝试使用 $stateParams 从 url 读取“lan”参数,但它仍然未定义:

/*AppCtrl*/
$scope.init = function () {
    console.log($stateParams); // prints Object {lan: "en"}
    console.log($stateParams.lan); // prints undefined
    $timeout(function () {console.log($stateParams.lan);}, 500); //prints "en"
}

这很奇怪,因为我可以看到它打印带有我无法访问的 .lan 属性的 $stateParams。

我还像这样配置了 $stateProvider:

$stateProvider
    .state('root', {
        url: '/{lan:(?:pt|en)}',
        abstract: true,
        template: '<div ui-view=""></div>',
        params: { lan: { value: 'pt' } },
    })
    .state('home', {
        parent: 'root',
        url: '/',
        templateUrl: '/front/main/views/front-main.client.view.html'
    });

这样做的正确方法是什么?

【问题讨论】:

    标签: angularjs angular-ui-router


    【解决方案1】:

    方法是从这里移除ng-controller

    <body ng-controller="AppCtrl" ng-init="init()">
    

    并将其移动到状态

    .state('root', {
        url: '/{lan:(?:pt|en)}',
        abstract: true,
        template: '<div ui-view=""></div>',
        params: { lan: { value: 'pt' } },
        controller:'AppCtrl'
    })
    

    一般来说.. 州的 views 和他们的 controllers 是关于 UI-Router 世界...而不是 AngularJS ng-controller

    【讨论】:

      猜你喜欢
      • 2016-01-23
      • 1970-01-01
      • 2016-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多