Brandon Tran
Brandon Tran

Reputation: 33

How to get json data and construct a modal using Angular JS

When I click on the view details button, I want to request JSON data and then construct a modal view over the content.

HTML:

<a href="#">View Details 1</a>
<a href="#">View Details 2</a>
<a href="#">View Details 3</a>

Get JSON:

function MyCtrl($scope){
      $http.get('json/story.json').success(function(data){
        console.log(data);
        $scope.story = data;
    });
}

What is the best practices to run this MyCtrl function using angular.js when a user clicks on the detail button? Also the HTML above is being printed out using another controller. I hope there is some way to bind the clicks versus hard-coding ID's and such in the links.

Upvotes: 2

Views: 5728

Answers (3)

Mark Rajcok
Mark Rajcok

Reputation: 364697

Put your server communication code (i.e., $http stuff) into an Angular service. Inject that service into the controller that displays your HTML and into your controller that is associated with your modal view (if you have one).

Have your links invoke functions on the controller that will interact with the service to fetch the data. Have your modal controller $watch for the data.

<div ng-controller="MyCtrl">
<a href="" ng-click="getDataset1()">View Details 1</a>

Controllers:

function MyCtrl($scope, myService) {
   $scope.getDataset1 = function() {
       myService.getDataset1();  // populates myService.modalData
   };
}

function ModalCtrl($scope, myService) {
   $scope.showModal = false;
   $scope.$watch(myService.modalData, function(data) {
      $scope.modalData = data;
      $scope.showModal = true;
   });
}

Upvotes: 1

pkozlowski.opensource
pkozlowski.opensource

Reputation: 117370

A complete example of CRUD edit with asynchronous data (here simulated via $timeout) can be seen here: http://plnkr.co/edit/EAabx4?p=preview

It uses the $dialog service from the http://angular-ui.github.com/bootstrap/ repository. This example uses Bootstrap's CSS but a template is fully customizable.

The nice part about the $dialog service is that it nativelly works with AngularJS promises so you don't have to copy things to a scope, use watches etc.

Upvotes: 1

jszobody
jszobody

Reputation: 28911

You can call methods in your controller like this:

<a href="#" ng-click="getDetails()">View Details</a>

And then in the controller:

$scope.getDetails = function() {
    $http.get(...).success(function(data){
        $scope.story = data;
    });
}

Upvotes: 4

Related Questions