前端外刊评论 2018-03-08
今天使用angularjs的ng-options实现一个DropDownList下拉列表。
准备ASP.NET MVC的model:


public class MobilePhone
{
public int ID { get; set; }
public string Name { get; set; }
}Source Code接下来,还得准备Entity:



public IEnumerable<MobilePhone> MobilePhones()
{
return new List<MobilePhone>()
{
{new MobilePhone() { ID = , Name = "华为" }},
{new MobilePhone() { ID = , Name = "苹果" }},
{new MobilePhone() { ID = , Name = "小米" }},
{new MobilePhone() { ID = , Name = "中兴" }}
};
}
}Source Code
创建ASP.NET MVC的Controller,一个是视图Action,另一个是数据Action:


public class PhoneController : Controller
{
// GET: Phone
public ActionResult Index()
{
return View();
}
public JsonResult GetMobilePhones()
{
MobilePhoneEntity mpe = new MobilePhoneEntity();
var model = mpe.MobilePhones();
return Json(model, JsonRequestBehavior.AllowGet);
}
}Source Code
最后,我们需要准备一个angularjs的Controller:


pilotApp.controller('PhoneCtrl', ['$http', '$location', '$rootScope', '$scope',
function ($http, $location, $rootScope, $scope) {
var obj = {};
$http({
method: 'POST',
url: '/Phone/GetMobilePhones',
dataType: 'json',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
data: JSON.stringify(obj),
}).then(function (response) {
$scope.Phones = response.data;
});
}]
);Source Code不管是ASP.NET MVC还是AngularJs程序代码均准备好,现在我们需要在ASP.NET MVC视图实现下拉列表:


@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div ng-app="PilotApp" ng-controller="PhoneCtrl">
<select ng-model="ddlPhones" ng-options="MobilePhone.Name for MobilePhone in Phones"></select>
</div>
<script src="~/Angularjs/app.js"></script>
<script src="~/Angularjs/PhoneController.js"></script>Source Code上面有句ng-options绑定的表达式中,名词所来自何处,可参考下图指示:
动态效果演示: