前端的MVC


为实现模块化和复用!

最简单的控制器:

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值