Mohaideen Ismail
Mohaideen Ismail

Reputation: 314

Can't get the datas in angularJs

I have html page like

<div ng-controller="userListControl">
...
</div>
<div ng-controller="userDetailsControl">
....
</div>

And i have angular Js code is

var userDirectory = angular.module('userDirectory',[]);
    userDirectory.controller("userListControl", ['$scope','$http', function($scope, $http)
        {    
            $http.get('data/userData.json').success (function(data){
            $scope.users = data;
            $scope.users.doClick = function(user,event) {
                userInfo(user);
            }
        });
    }]);

    function userInfo(users)
    {
        console.log(user);
        userDirectory.controller("userDetailsControl", function($scope)
        {  
            console.log('well')  
            $scope.user = users;
            console.log($scope.user)

        });
}

Here Everything is working fine. But when we are calling click event, That userInfo called with particular Data. But Second controller gives an error(angular js Error).

I am new one in angular jS. I dont know this logic is correct or not.

I have list items in first Controller. When we are clicking on list, It gets data from particular list and passed to another design. That design have detailed data. So the 2nd controller shows particular list detailed Section

Upvotes: 0

Views: 40

Answers (1)

New Dev
New Dev

Reputation: 49590

First, There is no need to declare your controller inside a function - I don't think that you're trying to lazy-load controllers. Make it available to your app when it starts.

Second, you need to pass data to the userDetailsControl controller. There are various ways to do this, but here you could just use the $rootScope.

var userDirectory = angular.module('userDirectory',[]);
userDirectory.controller("userListControl", function($scope, $rootScope, $http)
{
  $scope.selectUser = function(user){
    $rootScope.selectedUser = user;
  }
  $http.get('data/userData.json')
    .success (function(data){
       $scope.users = data;
    });
})

.controller("userDetailsControl", function($scope, $rootScope){
  $rootScope.$watch("selectedUser", function(newVal){
    $scope.user = newVal;
  }
}

and in your HTML:

<div ng-controller="userListControl">
  <button ng-repeat="user in users" ng-click="selectUser(user)">{{user.name}}</button>
</div>
<div ng-controller="userDetailsControl">
  <div>{{user.name}}</div>
  <div>{{user.otherDetails}}</div>
</div>

Upvotes: 1

Related Questions