前端的MVC

来源:互联网 发布:成浪网络 编辑:程序博客网 时间:2024/05/29 09:32

为实现模块化和复用!

最简单的控制器:

view:

<!doctype html><html ng-app><head><meta charset="utf-8"><title>ag_test</title></head><body><div ng-controller="CommonController"><div ng-controller="Controller1"><p>{{ greeting.text }},Angular</p><button ng-click="test1()">test1</button></div><div ng-controller="Controller2"><p>{{ greeting.text }},Angular</p><button ng-click="test2()">test2</button></div><button ng-click="commonFn()">通用</button></div></body><script src="js/angular.min.js"></script><script src="js/mvc.js"></script></html>


Controller:

function CommonController($scope){$scope.commonFn=function(){    alert("这里是通用功能!");    };}function Controller1($scope) {    $scope.greeting = {        text: 'Hello1'    };    $scope.test1=function(){    alert("test1");    };}function Controller2($scope) {    $scope.greeting = {        text: 'Hello2'    };    $scope.test2=function(){    alert("test2");    }}
主意:

不要复用Controller

不要使用DOM

不要在Controller做数据格式化,要使用ng表单控件

不要使用数据过滤,有$filter服务


Model方面:

最简单的model:

<input ng-model="greeting.text"><p>{{ greeting.text }},Angular</p>

复用视图:

var myModule = angular.module("MyModule",[]);myModule.directive("hello",function(){    return {        restrict:'E',        template:'<div>Hello World!</div>',        replace:true    }});

直接使用: <hello></hello> 可得到“Hello World”


作用域问题:

js:

function Ctrl($scope,$rootScope){    $scope.name           = 'Hello';    $rootScope.department = 'Angular';}function List($scope){    $scope.name = ['xjh','czg','zaq','hsj'];}
view:

<div ng-controller="Ctrl">        {{name}},world!        </div>        <div ng-controller="List">        <ul>        <li ng-repeat="infos in name">        {{infos}} from {{department}}        </li>        </ul>        </div>

关于$scope:$watch()/$apply()

是POJO

是表达式(作用域)

是树形结构,与DOM标签平行

可以继承父作用域属性和方法

每个Angular应用只有一个根$scope对象(在ng-app上)

可以传播事件,向上或向下

是MVC基础,也是双向数据绑定的基础

调试:angular.element($0).scope()

scope生命周期:Creation-Watcher registration-Model mutation-Mutation observation-Scopedestruction



$watch()/$apply()
0 0