Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Angular中的MVC模型 #29

Open
Wscats opened this issue Nov 20, 2016 · 0 comments
Open

Angular中的MVC模型 #29

Wscats opened this issue Nov 20, 2016 · 0 comments

Comments

@Wscats
Copy link
Owner

Wscats commented Nov 20, 2016

简介

MVC是一种使用 MVC(Model View Controller 模型-视图-控制器)设计模式,该模型的理念也被许多框架所吸纳,比如,后端框架(Struts、Spring MVC等)、前端框架(Angular、Backbone等)。在学习angular的过程中,我在网上查找关于angular MVC介绍的文章很少,有些文章也没有很直白地为初学者指明angular MVC到底是啥样貌,因此,今天我们就来谈谈MVC模型在angular的形态。

为了介绍angular MVC模型,我建立一个最简单的例子。该例子的启动展示结果为:
image

下面我会逐一解释。

view

view指的是视图,在web前端工程中,view往往指的是HTML代码。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="css/bootstrap.css" type="text/css">
</head>
<body ng-app="app">

    <div class="col-md-4 col-md-offset-4" ng-controller="InputController">
        模型数据: <input type="text" class="text-primary" ng-model="book.title">
    </div>

    <script src="js/angular.js"></script>
    <script src="js/demo1.js"></script>
</body>
</html>

model

model指的是模型数据,在java后端开发中,我们常常使用java为业务数据单独建模,然而,在前端中,我们也可以为数据建立模型。比如,下面的代码片段。

var book = {
        title: "angular"
}

我们为书籍建立一个数据模型对象,为了简单,我只为book声明了一个属性。

controller

controller指的是控制器,它的作用是控制model与view之间的交互。

angular.module("app", ["InputModule"]);

angular.module("InputModule", [])
.controller("InputController", ["$scope", function ($scope) {
    var book = {
        title: "angular"
    }
    $scope.book = book;
}]);

在此例中,我将模型数据book定义在angular的controller控制器中。要想将模型中的数据传递给视图,angular规定依附在$scope上的数据才能传递给视图。
总结
接下来,我用图来描述一下angular中MVC 的关联。
image

在全局使用ng-app指令,我就不多介绍了。

  • 1、通过在div中添加属性ng-controller="InputController",并设置属性值,通过angular解析关联到相关的控制器。也只有该div元素及其子元素,才能有权限使用InputController中的$scope对象上的模型数据。
  • 2、ng-model="book.title",通过angular解析,关联到其所处控制器中的$scope对象。根据指令的不同,关联到$scope对象上的方式也不同。ng-model指令将$scope对象与view对象的值进行双向绑定,犹如java中将对象的引用传给了view对象。ng-bind指令则是将$scope对象与view对象进行单向绑定,犹如java中将对象的副本值传给view对象。

原文:带你初识Angular中MVC模型

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant