AngularJS初学心得笔记

16. November 2016 笔记 0

①AngularJS的双向绑定真的很牛逼呢,再也不用使用JS或者Jquery遍历dom了,

<div ng-app=“myApp” ng-controller=“myCtrl”>
名字: <input ng-model=“name”>
<h1>你输入了: {{name}}</h1>
</div>

②用户验证输入

<form ng-app=“” name=“myForm”>
Email:
<input type=“email” name=“myAddress” ng-model=“text”>
<span ng-show=“myForm.myAddress.$error.email”>不是一个合法的邮箱地址</span>
</form>

判断用户输入是否正确,添加提示,一行代码搞定。

ng-model 指令可以为应用数据提供状态值(invalid, dirty, touched, error):

valid 用户输入正确的时候为true

invalid 输入错的时候为true,和valid相反

Dirty 值改变为true

Touched 如果通过触屏点击为true

通过input.ng-invalid {
background-color: lightblue;
}修改验证是失败时候的css样式,厉害吧。

③  rootScope 可作用于整个应用中。是各个 controller 中 scope 的桥梁。用 rootscope 定义的值,可以在各个 controller 中使用。

<div ng-app=”myApp” ng-controller=”myCtrl”>

<h1>姓氏为 {{lastname}} 家族成员:</h1>

<ul>
<li ng-repeat=”x in names”>{{x}} {{lastname}}</li>//$rootScope在循环对象内外都可以访问
</ul>

</div>

<script>
var app = angular.module(‘myApp’, []);

app.controller(‘myCtrl’, function($scope, $rootScope) {
$scope.names = [“Emil”, “Tobias”, “Linus”];
$rootScope.lastname = “Refsnes”;
});
</script>

④ 自定义服务

<div ng-app=”myApp” ng-controller=”myCtrl”>

<p>255 的16进制是:</p>

<h1>{{hex}}</h1>

</div>

<p>自定义服务,用于转换16进制数:</p>

<script>
var app = angular.module(‘myApp’, []);

app.service(‘hexafy’, function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
app.controller(‘myCtrl’, function($scope, hexafy) {
$scope.hex = hexafy.myFunc(255);
});
</script>

⑤http请求Json数据

<div ng-app=”myApp” ng-controller=”siteCtrl”>

<ul>
<li ng-repeat=”x in names”>
{{ x.Name + ‘, ‘ + x.Country }}
</li>
</ul>

</div>

<script>
var app = angular.module(‘myApp’, []);
app.controller(‘siteCtrl’, function($scope, $http) {
$http.get(“http://www.runoob.com/try/angularjs/data/sites.php”)
.success(function (response) {$scope.names = response.sites;});
});
</script>

⑥AngularJS Select选择框

<div ng-app=”myApp” ng-controller=”myCtrl”>

<select ng-model=”selectedName” ng-options=”x for x in names”>
</select>

</div>

<script>
var app = angular.module(‘myApp’, []);
app.controller(‘myCtrl’, function($scope) {
$scope.names = [“Google”, “Runoob”, “Taobao”];
});
</script>

⑦AngularJS点击事件 ng-click=””

<div ng-app=”myApp” ng-controller=”myCtrl”>

<button ng-click=”count = count + 1″>点我!</button>

<p>{{ count }}</p>

</div>
<script>
var app = angular.module(‘myApp’, []);
app.controller(‘myCtrl’, function($scope) {
$scope.count = 0;
});
</script>

⑧angularJS 包含

<div ng-include=”‘myUsers_List.htm'”></div>

加载代码片段,很实用呢。

{{}} 是angularJs的内置语法,相当于ng-bind,但{{}}会出现闪烁情况(数据没有加载完成时候),

ng-bind不会产生闪烁,它在数据加载完成之后才显示,使用{{}}是,添加上ng-cloak可以避免闪烁问题。

 


Leave a Reply

Your email address will not be published. Required fields are marked *