迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > Angular >

带你进入Angular js的大门

作者:迹忆 最近更新:2022/11/13 浏览次数:

介绍

这是我写的第一篇关于Angular.js的文章,但是我确信看完这篇文章将对你了解Angular.js的基本知识有很大的帮助。

首先需要指出什么是angular js,其实说白了angular js就是Javascript的一个类库,我们使用这个类库可以很容易的创建web页面。双向绑定是angular js其中的一个重要特征,这也是相对于其他的Javascript的类库来说angular js中很重要的特征。双向绑定即是当你修改任何属性的值的时候,相关联的html元素也将改变,你并不需要额外的去修改。

Angular js还为我们提供了MVVM(Model View ViewModel)的模型。MVVM的意思就是说Model是一个真实的对象,我们使用这个对象创建需要在页面显示的模型,并且调用视图模型。View(视图)即是我们需要输出的页面。

背景

如果你没有使用angular js或者其它的和angular js有相似功能的类库,比如knockout.js,那么当我们编写代码的时候将会写更多更复杂的代码。所以说使用angular js编写应用程序更快更高效,并且比其它的类库更容易管理。

代码使用

下面我们将通过一个简单的例子来逐渐的了解angular js。

为了更好的理解angular js的知识,我们使用asp.net作为后台的应用程序来实现简单的增删改查的操作,并且在这个例子中我们使用的是静态列表形式来展现增删改查的操作。

在数据模型中有5个属性,UserName、Address、Salary、IsMarried和Email。在视图中列出了这些属性的记录,并且在每一条数据后面都有一个删除和修改按钮。通过这些按钮我们能创建、修改和删除静态列表。

现在首先让我们了解一下以下例子中使用到的属性的含义

data-ng-app——表明这是angular 要处理的元素

data-ng-controller——指定用来处理此元素的angular 控制器

<div id="divUserList" data-ng-app="userApp" data-ng-controller="userAppCtrl"> </div>

data-ng-bind——指定该元素绑定model中的哪个属性(上面列出的UserName、Address、Salary、IsMarried或者是Email)

<strong data-ng-bind="UserName"></strong>

比如UserName是Model的属性并且将该属性绑定到定义的元素

data-ng-repeat——用来指定循环的数据

<tr data-ng-repeat="x in UserData | limitTo:20"  >

使用上面的语法,我们对UserData这个angular 对象属性进行循环,取出里面的数据。limitTo:20表明最多循环20次,这是angular中的一个过滤器。当然angular.js中还可以使用其他的过滤器,比如uppercase、lowercase和currency等。

data-ng-click——用来绑定点击事件

<input type="button" id="btnDelete" value="Delete" data-ng-click="DeleteRow($index)" />

$index——表示循环中的索引

data-ng-model——将angular 模型应用于html dom中,这表示当修改input输入框中的值时相应的model中的属性也会改变

<input type="text" data-ng-model="UserName" required />

data-ng-disabled——通过该属性的值来禁用某个元素或者不禁用

<input type="button" id="btnSaveAll" value="Save" data-ng-click="SaveRecord()" data-ng-disabled="CheckRecord()" />

下面让我们看一下下面的代码

var angularuserApp = angular.module("userApp", []);
 
angularuserApp.controller("userAppCtrl", function ($scope, $http, $interval, $window,$timeout) {})

第一行代码创建了一个对象,这是由html dom中data-ng-app指定的。另一行代码创建了一个控制器,是由data-ng-controller指定的。

$http用来指定服务端的地址;$interval$timeout就类似于jquery中的interval和timeout,这两个变量在这个例子中只是定义但并没有被使用到,其工作原理和jquery中的相同;$window的定义和Javascript中的window对象相同,使用这个变量可以实现你想用window对象实现的效果。

下面是所有HTML代码

<div id="divUserList" data-ng-app="userApp" data-ng-controller="userAppCtrl">
    <table class="table-striped table-hover" style="width:100%;">
        <colgroup>
            <col style="width:15%;"/>
            <col style="width:25%;" />
            <col style="width:10%;" />
            <col style="width:10%;" />
            <col style="width:15%;" />
            <col style="width:10%;" />
            <col style="width:7%;" />
            <col style="width:7%;" />
        </colgroup>
        <thead>
            <tr>
                <th>User Name</th>
                <th>Address</th>
                <th>Email</th>
                <th>Salary</th>
                <th>Is Married</th>
            </tr>
        </thead>
        <tbody>
            <tr data-ng-repeat="x in UserData | limitTo:20"  >
                <td>
                    <strong data-ng-bind="x.UserName"></strong>
                </td>
                <td><span data-ng-bind="x.Address"></span></td>
                <td><span data-ng-bind="x.Email"></span></td>
                <td><span data-ng-bind="x.Salary"></span></td>
                <td><span data-ng-bind="x.IsMarried"></span></td>
                <td><input type="button" id="btnEdit" value="Edit" data-ng-click="EditRow(x)" /> </td>
                <td><input type="button" id="btnDelete" value="Delete" data-ng-click="DeleteRow($index)" /> </td>
            </tr>
        </tbody>
    </table>
    <br />
    <br />
    <form name="myform" novalidate>
        <h3> Edit User Information </h3>
        <table class="table-striped table-hover" style="width:100%;">
            <tr>
                <td>
                    User Name :
                </td>
                <td>
                    <input type="text" data-ng-model="UserName" required />
                </td>
            </tr>
            <tr>
                <td>
                    Address :
                </td>
                <td>
                    <input type="text" data-ng-model="Address" required />
                </td>
            </tr>
            <tr>
                <td>
                    Email :
                </td>
                <td>
                    <input type="email" data-ng-model="Email" />
                </td>
            </tr>
            <tr>
                <td>
                    Salary :
                </td>
                <td>
                    <input type="number" data-ng-model="Salary" />
                </td>
            </tr>
            <tr>
                <td>
                    Is Married :
                </td>
                <td>
                    <input type="checkbox" data-ng-model="IsMarried" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="button" id="btnSaveAll" value="Save" data-ng-click="SaveRecord()" data-ng-disabled="CheckRecord()" />
                    <input type="button" id="btnClear" value="Clear" data-ng-click="ClearRecord()" data-ng-disabled="CheckRecord()" />
                </td>
 
            </tr>
        </table>
    </form>
</div>
<script>
    var angularuserApp = angular.module("userApp", []);
    angularuserApp.controller("userAppCtrl", function ($scope, $http, $interval, $window, $timeout) {
        //==Intit Value================
        $scope.UserName = "";
        $scope.Address = "";
        $scope.Email = "";
        $scope.Salary = null;
        $scope.IsMarried = null;
        //==Intit Value================
        $scope.LoadIntialData = function () {
            var routeurl = '@Url.Action("GetData", "User")';
            $http.get(routeurl).success(function (data) {
                $scope.UserData = data;
            }).error(function (e) {
                // error handling
            });
        }
        $scope.LoadIntialData();
        $scope.DeleteRow = function (index) {
            $scope.UserData.splice(index, 1);
            //==================if you use real time application then need to call to conroller from remove record from db=======
        }
        $scope.EditRow = function (ele) {
            $scope.UserName = ele.UserName;
            $scope.Address = ele.Address;
            $scope.Email = ele.Email;
            $scope.Salary = ele.Salary;
            $scope.IsMarried = ele.IsMarried;
        }
        $scope.SaveRecord = function () {
            var invalidfiled = "";
            if (!$scope.myform.$valid) {
                return;
            }
            else {
                var IsItemUpdate = false;
                $.each($scope.UserData, function (i, n) {
                    if (n.UserName == $scope.UserName && n.Address == $scope.Address) {
                        IsItemUpdate = true;
                        n.Email = $scope.Email;
                        n.Salary = $scope.Salary;
                        n.IsMarried = $scope.IsMarried;
                    }
                });
                if (IsItemUpdate == false) {
                    var obj = new Object();
                    obj.UserName = $scope.UserName;
                    obj.Address = $scope.Address;
                    obj.Email = $scope.Email;
                    obj.Salary = $scope.Salary;
                    obj.IsMarried = $scope.IsMarried;
                    $scope.UserData.unshift(obj);
                }
                $scope.ClearRecord();
                //==================if you use real time application then need to call to conroller from save record from db=======
            }
        }
        $scope.CheckRecord = function () {
            if ($scope.UserName != "" && $scope.Address != "")
                return false;
            else
                return true;
        }
        $scope.ClearRecord = function () {
            $scope.UserName = "";
            $scope.Address = "";
            $scope.Email = "";
            $scope.Salary = null;
            $scope.IsMarried = null;
        }
    });
</script>

下面是控制器的实现代码

public class UserController : Controller
   {
       //
       // GET: /User/
 
       public ActionResult Users()
       {
           return View();
       }
 
       public JsonResult GetData()
       {
           List<User> objList = new List<User>();
 
           //==Create the test data for in view  ============================
           User objuser = new User();
           objuser.UserName = "Pragnesh Khalas";
           objuser.Address = "B-25 Swaminarayan Park Naroda Ahmedabad";
           objuser.Email = "pragnesh@gmail.com";
           objuser.Salary = 9000;
           objuser.IsMarried = true;
           objList.Add(objuser);
 
           objuser = new User();
           objuser.UserName = "Rahul Patel";
           objuser.Address = "A-40 Navkar Soci. Ahmedabad";
           objuser.Email = "rahul@gmail.com";
           objuser.Salary = 8000;
           objuser.IsMarried = true;
           objList.Add(objuser);
 
           objuser = new User();
           objuser.UserName = "Bhavin Patel";
           objuser.Address = "D-10 Bharat Soci. Ahmedabad";
           objuser.Email = "bhavin@gmail.com";
           objuser.Salary = 6000;
           objuser.IsMarried = true;
           objList.Add(objuser);
 
           return Json(objList, JsonRequestBehavior.AllowGet);
       }
 
   }

下面是模型代码

public class User
{
    [Required]
    public string UserName { get; set; }
 
    [Required]
    public string Address { get; set; }
 
    [EmailAddress]
    public string Email { get; set; }
 
 
    public double? Salary { get; set; }
    public bool? IsMarried { get; set; }
}

以上就是本文的整体内容,希望对你有所帮助。

原文:Beginning Understanding of AngularJs

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

JavaScript POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便