如何让在MVC使用angularjs从控制器到$范围数据 [英] how to get data from controller to $scope in mvc using angularjs

查看:179
本文介绍了如何让在MVC使用angularjs从控制器到$范围数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的角JS,我使用与mvc5应用角度JS。我创建了JS的角度模块和控制器。我有一个行动视图用户控制器(MVC5)。我们需要显示该视图中的所有客户,我想用NG-重复在这里。

I am new to angular js, I am using angular js with mvc5 application. I have created a module and controller in the js for angular. I have one action "View" in customer controller(MVC5). We need to show the all the customer in this view and i want to use "ng-repeat" here.

我的问题是我得到客户的集合作为模型,previously我是做模型的foreach循环显示的客户。现在怎么我可以添加到模型范围$数据容器,这样我可以在NG-重复使用。

My problem is i am getting collection of customer as model, previously i was making foreach loop of model to show the customers. Now how i can add model into $scope data container so that i can use in ng-repeat.

推荐答案

什么你一直在做,直至现在呈现在服务器上的客户集合直奔HTML返回给客户端。你想最好做的是使没有收集客户的HTML和有超过$ HTTP调用服务,您的API控制器给你的数据。从那里是很容易,你

What you have been doing till now is rendering the customers collection on server straight to the HTML returned to the client. What you want to do ideally is to render the HTML without the customers collection and have a call over $http service to your API controller to give you the data. From there is is easy, you

我建议阅读:

  • http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
  • https://docs.angularjs.org/api/ng/service/$http
  • https://docs.angularjs.org/api/ng/directive/ngRepeat

在你的控制器使用HTTP $远离最好的做法,但为了简化...在控制器的$ HTTP调用可能看起来像这样:

Using $http in your controllers is far away from the best practice, but for simplification...the $http call in your controller could look like this:

$http({method: 'GET', url: '/api/customers'}).
    success(function(data, status, headers, config) {
        $scope.customers = data;
    }).
    error(function(data, status, headers, config) {
      alert('error');
    });

然后在视图ngRepeat:

Then you ngRepeat in the view:

  <ul>
    <li ng-repeat="customer in customers">
       {{customer.name}}
    </li>
  </ul>

这篇关于如何让在MVC使用angularjs从控制器到$范围数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆