0

I have been ploughing into AngularJS and am trying to get my head around how everything links together but I've become a bit stuck.

How can I pass a variable to change the JSON that is loaded and shown on the page? I thought it would be a button click and the directive would talk to the controller, but how I'm not so sure.

If i have my JSON as something like this as in controller...

var id = 'peter'; 
var person = $resource('http://myjson.com/'+id+'.json')

I can't figure out how I would change the id based on button clicks for example.

Any help is greatly appreciated

1 Answer 1

1

I'll try to explain as simple as possible, you can pass data as argument to a function from HTML to controller using the ngClick directive. The function inside the controller will be invoked because it has a binding to the ngClick directive using the $scope.

Example:

html:

<div ng-app="App"  ng-controller="ctrl">
    <div ng-repeat="itemId in items">
        <button ng-click="myClickFunc(itemId)">click {{itemId}}</button>
    </div>

</div>

js:

var app=angular.module('App', ['ngResource']);

function ctrl($scope,$resource){
    $scope.items=[1,2,3,4];

    $scope.myClickFunc=function(itemId){

        var person = $resource('http://myjson.com/get/:id');
        person.get({id: itemId}).$promise.then(function(data) {
           // success
           $scope.myData = data;
        }, function(errResponse) {
           // fail
        });
    }

Live example: http://jsfiddle.net/choroshin/zJ5G6/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.