简体   繁体   English

如何使用Angular JS获取json数据并构造模式

[英]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. 当我单击视图详细信息按钮时,我想请求JSON数据,然后在内容上构建一个模式视图。

HTML: HTML:

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

Get JSON: 获取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? 当用户单击详细信息按钮时,使用angular.js运行此MyCtrl函数的最佳实践是什么? Also the HTML above is being printed out using another controller. 另外,上面的HTML正在使用另一个控制器打印出来。 I hope there is some way to bind the clicks versus hard-coding ID's and such in the links. 我希望可以通过某种方式将点击次数与硬编码ID绑定在一起。

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;
    });
}

Put your server communication code (ie, $http stuff) into an Angular service . 将您的服务器通信代码(即$ http东西)放入Angular服务 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). 将该服务注入到显示HTML的控制器以及与模式视图关联的控制器中(如果有的话)。

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. 让您的模态控制器$ watch查看数据。

<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;
   });
}

A complete example of CRUD edit with asynchronous data (here simulated via $timeout ) can be seen here: http://plnkr.co/edit/EAabx4?p=preview 可以在此处看到使用异步数据进行CRUD编辑的完整示例(此处通过$timeout模拟): http : //plnkr.co/edit/EAabx4?p=preview

It uses the $dialog service from the http://angular-ui.github.com/bootstrap/ repository. 它使用http://angular-ui.github.com/bootstrap/存储库中的$dialog服务。 This example uses Bootstrap's CSS but a template is fully customizable. 本示例使用Bootstrap的CSS,但是模板是完全可定制的。

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. 关于$dialog服务的好处是它可以与AngularJS promises一起使用,因此您不必将内容复制到作用域,使用手表等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM