Gautam Kumar
Gautam Kumar

Reputation: 727

Update other view based on selection of first view?

I am new to angularjs. I want to update profile based on click from data ul.

How to do it?

html :

<div ng-app="test">
    <div ng-controller="cont">
        <ul>
            <li ng-repeat="(key, val) in data">{{val.name}}</li>
        </ul>
        <ul id="profile-ul">
            <li>profile should repeat here</li>
        </ul>    
    </div>    
</div> 

JS :

var data = [{ 
    'name' : 'A',
    'profile' : ['A 1','A 2','A 3']
},
{ 
    'name' : 'B',
    'profile' : ['B 1','B 2','B 3']
}
]
var angApp = angular.module('test',[]);
angApp.controller('cont', ['$scope', function($scope){
    $scope.data = data;
}])

Here js fiddle to work with.

Upvotes: 0

Views: 34

Answers (2)

CodeVirtuoso
CodeVirtuoso

Reputation: 6448

Here it is:

http://jsfiddle.net/hh5kwf4n/

var data = [{ 
    'name' : 'A',
    'profile' : ['A 1','A 2','A 3']
},
{ 
    'name' : 'B',
    'profile' : ['B 1','B 2','B 3']
}
]
var angApp = angular.module('test',[]);
angApp.controller('cont', ['$scope', function($scope){
    $scope.data = data;
    $scope.profile = ['A','B','C'];    

    $scope.updateProfile = function(key) {
        $scope.selectedProfile = data[key];
    };
}])

and the HTML

<div ng-app="test">
    <div ng-controller="cont">
        <ul>
            <li ng-repeat="(key, val) in data" ng-click="updateProfile(key)">{{val.name}}</li>
        </ul>
        <ul id="profile-ul">
            <li ng-repeat="item in selectedProfile.profile">{{item}}</li>
        </ul>    
    </div>    
</div>   

Explanation: by putting {{selectedProfile.name}} in our view, we're telling the view to replace that with whatever is the value of given variable, which is our "model"

Next...by adding ng-click="updateProfile(key)" to a li tag, we're making sure that each time a li tag is clicked, updateProfile function will be called, and the key of current element will be passed to it.

And finally, in our controller, we have the function updateProfile which based on key passed to it, updates the value of our model - selectedProfile.

Now...as soon as model is updated, the view gets automatically updated, and that's it:)

Upvotes: 1

Gautam Kumar
Gautam Kumar

Reputation: 727

Figured out my self :

html :

<div ng-app="test">
    <div ng-controller="cont">
        <ul>
            <li ng-click="updateKey(val)" ng-repeat="(key, val) in data">{{val.name}}</li>
        </ul>
        <ul id="profile-ul">
            <li ng-repeat="val in profile">{{val}}</li>
        </ul>    
    </div>    
</div> 

JS :

var data = [{ 
    'name' : 'A',
    'profile' : ['A 1','A 2','A 3']
},
{ 
    'name' : 'B',
    'profile' : ['B 1','B 2','B 3']
}
]
var angApp = angular.module('test',[]);
angApp.controller('cont', ['$scope', function($scope){
    $scope.data = data;
    $scope.updateKey = function(data){
        $scope.profile = data.profile;
    }
}])

here is jsfiddle

Upvotes: 0

Related Questions