AngularJs入门(二)

隐藏和显示

指令ng-show和ng-hide 这两个指令的功能是等价的,但运行效果正好相反。也就是说ng-show为true时将会显示,为false时将会隐藏,而hide则相反。

 1 <!DOCTYPE html>
 2 <html ng-app="">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 5     <title></title>
 6 </head>
 7 <body ng-controller="myCtrl">
 8     <button ng-click="toggleP()">按钮</button>
 9     <p ng-show="pShow">Hello World</p>
10     <script src="js/angular-1.2.16.js"></script>
11     <script>
12         function myCtrl($scope)
13         {
14             $scope.toggleP = function ()
15             {
16                 $scope.pShow = !$scope.pShow;
17             }
18         }
19     </script>
20 </body>
21 </html>
View Code

CSS类和样式

只要使用表达式{{}}进行数据绑定就可以动态的设置css类和样式了,设置还可以在模板中构造css类名 的部分匹配。

 1 <!DOCTYPE html>
 2 <html ng-app="">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 5     <title></title>
 6     <style>
 7         .is-menu-true {
 8             color:red;
 9         }
10     </style>
11 </head>
12 <body ng-controller="myCtrl">
13     <button ng-click="toggleP()">按钮</button>
14     <p class="is-menu-{{isRed}}">Hello World</p>  
15     <script src="js/angular-1.2.16.js"></script>
16     <script>
17         function myCtrl($scope)
18         {
19             $scope.toggleP = function ()
20             {
21                 $scope.isRed = true;
22             }
23         }
24     </script>
25 </body>
26 </html>
View Code

也可以使用style={{expression}},虽然这种方式具有很大的灵活性,但是也有一些不利的地方,当需要 同时在模板和Javascript中使用时,它很快就会变得无法维护,进而无法正确的创建CSS。正是由于这些原因 Angular提供了ng-class和ng-style指令。两个指令的写法如下:ng-class={className:bool,className:bool} ng-style={color:expression}

 1 <!DOCTYPE html>
 2 <html ng-app="">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 5     <title></title>
 6     <style>
 7         .error {
 8             color:red;
 9         }
10         .warning {
11             color:orange;
12         }
13     </style>
14 </head>
15 <body ng-controller="myCtrl">
16     <button ng-click="error()">Error</button>
17     <button ng-click="warning()">Warning</button>
18     <p ng-class="{error:IsError,warning:IsWarning}">Hello World</p>
19     <script src="js/angular-1.2.16.js"></script>
20     <script>
21         function myCtrl($scope)
22         {
23             $scope.IsError = false;
24             $scope.IsWarning = false;
25             $scope.error = function ()
26             {
27                 $scope.IsError = true;
28                 $scope.IsWarning = false;
29             };
30             $scope.warning = function ()
31             {
32                 $scope.IsWarning = true;
33                 $scope.IsError = false;
34             };
35         }
36     </script>
37 </body>
38 </html>
View Code

src和href

当在<img>或者<a>标签上进行数据绑定时,由于浏览器会优先使用并行的方式来加载图片和其他内容,所以Angular 没有机会拦截到数据绑定请求,所以angular使用了ng-src和ng-href。

原文地址:https://www.cnblogs.com/zengm/p/3956506.html