如何在angularjs

时间:2015-11-11 12:04:48

标签: angularjs

以下是我的播放列表json数据。

{
    "id":18,
    "file":{"url":"/uploads/playlist/file/18/01_-_MashAllah.mp3"},
    "event_id":23,"created_at":"2015-11-11T10:33:52.000Z",
    "updated_at":"2015-11-11T10:33:52.000Z",
    "name":"01 - MashAllah.mp3"
}

现在我想将id和name绑定到不同的控制器,我正在做这样的事情

播放列表控制器

.controller('playlistsController',['$scope','playlists',function($scope,playlists) {

  $scope.playlists = playlists.query();


}]);

视图

<div ng-controller="playlistsController">
  <div ng-repeat="playlist in playlists">
    <div ng-controller='PlayerController'>

      <input type=hidden ng-model="ID" ng-value="playlist.id">
      <input type=hidden ng-model="name" ng-value="playlist.name">

    </div>
  </div>
</div>

并在控制器中

.controller('PlayerController',['$scope',function($scope) {

  console.log($scope.ID);
  console.log($scope.name);


}]);

但控制台显示未定义。

我不知道我哪里出错了,因为我是棱角分明的新人。

3 个答案:

答案 0 :(得分:0)

在进行任何绑定之前,您需要先将播放列表数据输入控制器。通常,这是通过您注入的服务,它向控制器提供数据。一旦播放列表数据存在,您就可以将$scope.playlists绑定到它,并且您的ng-repeat将起作用。

或者,只是为了使绑定起作用,在控制器中定义播放列表数据,并将列表直接分配给$ scope。这应该让你看到绑定有效,然后你可以根据对你有意义的最佳实践来重构JSON数据的加载。

答案 1 :(得分:0)

交换控制器和ng-repeat,您不希望为阵列中的每个对象创建控制器。改变你的模型!

<div ng-controller='PlayerController'>
    <div ng-repeat="playlist in playlists">
        <input type=hidden ng-model="playlist.id">
        <input type=hidden ng-model="playlist.name">
    </div>
</div>

然后将您的数据放入控制器

.controller('PlayerController',['$scope',function($scope) {

 $scope.playlists = [{
     "id":18,
     "file":{"url":"/uploads/playlist/file/18/01_-_MashAllah.mp3"},
     "event_id":23,"created_at":"2015-11-11T10:33:52.000Z",
     "updated_at":"2015-11-11T10:33:52.000Z",
     "name":"01 - MashAllah.mp3"
 }]
}]);

答案 2 :(得分:0)

你必须把这个代码放到COTROLLER

controller('PlayerController',['$scope',function($scope) {
        $scope.playlists = [{
        "id":18,
        "file":{"url":"/uploads/playlist/file/18/01_-_MashAllah.mp3"},
        "event_id":23,"created_at":"2015-11-11T10:33:52.000Z",
        "updated_at":"2015-11-11T10:33:52.000Z",
        "name":"01 - MashAllah.mp3"
    },{
        "id":19,
        "file":{"url":"/uploads/playlist/file/18/01_-_MashAllah.mp3"},
        "event_id":23,"created_at":"2015-11-11T10:33:52.000Z",
        "updated_at":"2015-11-11T10:33:52.000Z",
        "name":"01 - test.mp3"
    }];
        $scope.getvalue = function(val){
        console.log(val.id)
        console.log(val.name)
    }
}

在HTML中

<div ng-controller='PlayerController'>
   <div ng-repeat="playlist in playlists">
     <input type="hidden" ng-model="playlist.id" ng-init="getvalue(playlist)">
     <input type="hidden" ng-model="playlist.name" >
   </div>
</div>

<强> RESULT

重复数组时,您将获得同一控制器上的数据

18
01 - MashAllah.mp3
19
01 - test.mp3

这可能会对你有帮助!