当我使用$ stateParams时,map返回-1

时间:2015-02-21 18:11:30

标签: javascript angularjs angular-ui-router

我尝试将变量传递给页面,因此我的网址为:http://localhost/project/#/app/intro/1

并路由到我的控制器,一切正常,但当我在控制器中尝试map一个数组时,我遇到了问题!

我的代码是:

console.log($stateParams.userId); // return 1
var ePos = $rootScope.data.users.map(function (x) {
    return x.id;
}).indexOf($stateParams.userId);
console.log(ePos); // return -1

但是当我尝试使用静态数据时,一切都很好

  console.log($stateParams.userId); // return 1
    var ePos = $rootScope.data.users.map(function (x) {
        return x.id;
    }).indexOf(1);
    console.log(ePos); // return 0

1 个答案:

答案 0 :(得分:1)

我创建了working plunker here

此处的问题出现在type - ID是string,而我们需要int。检查此示例

// here we force ui-router to act with id as INT
.state('int', {
   url: "/int/{id:int}",
   templateUrl: 'tpl.html',
   controller: 'MyCtrl',
})
// here we leave it as is - so it is a string "1"
.state('str', {
   url: "/str/:id",
   templateUrl: 'tpl.html',
   controller: 'MyCtrl',
})

这些链接

// these will return id as a 'number'
<a href="#/int/1">int/1</a>
<a ui-sref="int({id:2})">int({id:2})</a>

// these will have string as id
<a href="#/str/3">str/3</a>
<a ui-sref="str({id:4})">str({id:4})</a>

检查example here

EXTEND(and extended plunker

根据评论,我们可以有这样的州:

.state('app', {
  url: "/app",
  templateUrl: 'tpl.app.html',
})
.state('app.userIntro', {
  url: "/intro/{userId:int}",
  views: {
    'menuContent': {
      controller: 'UserIntroCtrl',
      templateUrl: "templates/intro.html"
    }
  }
})

电话可能是这样的:

<a href="#/app/intro/1">app/intro/1</a>
<a href="#/app/intro/2">app/intro/2</a>
<a ui-sref="app.userIntro({userId:3})">int({userId:3})</a>
<a ui-sref="app.userIntro({userId:4})">int({userId:4})</a>

检查extended version