双向数据绑定,用的是ng-model;

代码如下

一、简单绑定

,这里的input内容和name是一样的,相互绑定在一起的:

<!DOCTYPE html>
<
html ng-app="appModule">
<
head lang="en">
<
meta charset="UTF-8">
<
title></title>
</
head>
<
body ng-controller="appCtrl">
{{name}}<input type="text" ng-model="name"
/>
</
body>
<
script src="../angular.js"></script>
<
script>
var app=angular.module("appModule",[]);
app.controller("appCtrl",function($scope){
$scope.name="broszhu"
})
</
script>
</
html>

但是这么绑定有一个缺点,就是刷新的时候,每次都先显示表达式{{name}},然后才会显示绑定后的内容;可以用下面的方法来解决这个问题;用ng-bind=”name”就可以了

<body ng-controller="appCtrl">
<
span ng-bind="name"></span>
<
input type="text" ng-model="name"/>
</
body>

二、绑定函数:除了绑定字符串,还可以绑定函数;IE8,9不兼容angular;

<body ng-controller="appCtrl">
<!--<span ng-bind="name"></span>-->
<span ng-click="talk(name)">
点击我</span>
</
body>
<
script src="../angular.js"></script>
<
script>
var app=angular.module("appModule",[]);
app.controller("appCtrl",function($scope){
$scope.name="broszhu";
$scope.talk=function(name){
alert("hello "+name)
};
})
</
script>

三,绑定表单,并建立一个服务器来接收表单要保存的值;

<!DOCTYPE html>
<
html ng-app="appModule">
<
head lang="en">
<
meta charset="UTF-8">
<
title></title>
<
link rel="stylesheet" href="bootstrap.css"/>
</
head>
<
body ng-controller="appCtrl">
<
div class="form-group">
<
label for="username" class="control-label">用户名</label>
<
input type="text" id="username" ng-model="user.username" class="form-control"/>
</
div>
<
div class="form-group">
<
label for="password" class="control-label">密码</label>
<
input type="text" id="username" ng-model="user.password" class="form-control"/>
</
div>
<
div class="form-group">
<
button class="btn btn-default" ng-click="get()">获取</button>
<
button class="btn btn-default" ng-click="set()">设置</button>
<
button class="btn btn-danger" ng-click="reset()">重置</button>
<
button class="btn btn-danger" ng-click="save()">保存</button>
</
div>
</
body>
<
script src="angular.js"></script>
<
script>
var app=angular.module("appModule",[]);
app.controller("appCtrl",function($scope,$http){//这里需要注入$http
$scope.user={};
$scope.get=function(){
alert(JSON.stringify($scope.user))
};
$scope.set=function(){
$scope.user={username:"broszhu",password:"123456"};
};
$scope.reset=function(){
$scope.user={};
};
$scope.save=function(){
//ajax来保存$scope.user
$http({
url:'/user/add',
method:'POST',
data:$scope.user
}).success(function(data){
console.log($scope.user);
alert(data);
}).
error(function(err){
alert('err',err);
console.log(err);
})
};
})
</
script>

建立一个server来监听8080端口

var express = require('express');
var app = express
();
var bodyParser =
require('body-parser');
app.
use(express.static(__dirname));
app.
use(bodyParser.json());
app.post('/user/add',function(req,res
){
res.setHeader('Access-Control-Allow-Origin','*');
console.log(req.body);
//res.statusCode = 500;//出现500,会打印服务器错误;
res.end("OK")
});
app.listen(8080
);

 

 

~~~~~~