Angular1.0

公司会议室组织分享,两个小时困死我了,一点凌乱笔记:

$http.get和promise一样有then方法,成功,失败
jquery each遍历对象i,n

ng-app
ng-controller   数据绑定库   ng-config   ng-run
ng-module   一些内部模块,已经封装好的功能


ng-bind和{{}}异曲同工共  里面加竖线过滤,内部js语法兼容
与$scope的关系

ng-include就相当于data-html引用外部html
ng-pattern 可以用正则(就是ng-module没有的,比如tel,可以自己定义)
ng-show

ng-repeat 重复 x in arr,中间用x.键值,x就是某i对应的
<tr ng-repeat="x in arr">
    <td>{{x."time"}}</td>
    <td>{{x."name"}}</td>
    <td>{{x."price"}}</td>
</tr>
遍历数组 x in x

ng-class
ng-minlength 用于input规范长度
ng-maxlength

<select>的optionn遍历
已选中的 selectedNames 只要是select标签上 ng-module写的值
外面还是要套<form>

<input>的欸不加requited
type="Email"
$dirty 判断器
$valid 判断器
$invalid 判断器
$pristine
$error.reqired 判断
$error.email 判断

以下是在codecademy做的练习,做完几乎全忘。。

UNIT 1: YOUR FIRST APP

Lesson: Your First App
Get up and running quickly by building an AngularJS app from scratch.

Quiz: Your First App
Try this Codecademy Pro Quiz free!
PRO TRIAL
Project: Bolt Network 1 In this project, you'll create a movie review board using a controller and a view. Project: Pizza Planet In this project, you'll create a restaurant menu using filters and directives. Project: MOVE Log In this project, you'll create an exercise tracking app using directives. UNIT 2: DIRECTIVES Lesson: Directives Learn how to use directives to make standalone UI components. Quiz: Directives
Project: Bolt Network 2 In this project, you'll add custom directives to your movie review board. Project: Gameboard In this project, you'll create a custom directive that displays the score of a game. Project: Feedster In this project, you'll build a news feed using custom directives. UNIT 3: SERVICES Lesson: Services Use services to communicate with a server. Quiz: Services
Project: Outbox 1 In this project, you'll build an email app. Project: Top 10 In this project, you'll fetch movie data from the server and display it in a custom directive. UNIT 4: ROUTING Lesson: Routing Add routes to build powerful single-page applications. Quiz: Routing
Project: Outbox 2 In this project, you'll add to your email app by mapping URLs to views. Project: Calendar In this project, you'll create a calendar app with routes for each view. Project: Reader In this project, you'll create an e-reader app. UNIT 5: PUTTING IT ALL TOGETHER Project: NearMe 1 In this project, you'll build a location-based service using a third-party custom directive. Project: NearMe 2 In this project, you'll fetch data from the Wikipedia API and display it in your map. Project: NearMe 3 In this project, you'll map URLs to different views in your app using routing. ANGULARJS FINAL PROJECT Exclusive for Pro: AngularJS Final Project In this project you will create a web application using AngularJS. The app, Suggestion Box, will allow you to gather suggestions, upvote and comment on them. You’ll leave Codecademy’s learning environment and build locally, on your own computer, testing and running your web application in the browser.

AngularJS is a framework for building dynamic web apps

基本结构

So far this is our typical workflow when making an AngularJS app:

  1. Create a module, and use ng-app in the view to define the application scope.(在app.js中定义模块)
  2. Create a controller, and use ng-controllerin the view to define the controller scope.(在controller中丰满模块内的变量值)
  3. Add data to $scope in the controller so they can be displayed with expressions in the view.(在html中插值引用这些变量)

另外有一个angular最小例子:https://github.com/glitchtank/angular-seed-master

过滤器 filter

AngularJS comes with a few more built-in filters. Let's use two more.

In MainController.js inside$scope.product, add a third property named pubdate:

pubdate: new Date('2014', '03', '08')

我对third property的理解确实没有错,确实就是这么写的啊!可能拼写有误没有通过run,最后get code一看究竟:

$scope.product = {
  name: 'The Book of Trees',
  price: 19,
  pubdate: new Date('2014', '03', '08')
}

 
1.In index.html inside <p class="date">, display the product's pubdate.
2.Format the product's pubdate by piping it to the date filter.
3.Format the product's name by piping it to the uppercase filter.

<p class="title"> {{ product.name | uppercase }} </p>
<p class="price"> {{ product.price | currency }} </p>
<p class="date"> {{ product.pubdate | date }} </p>

原来所谓过滤器就是在html里面 | 号后面写的类型,比如date代表四位的日期,number代表数字。

html模板的循环adapter

<div ng-repeat="product in products" class="col-md-6"> 
  <div class="thumbnail"> 
    <img src="img/the-book-of-trees.jpg"> 
    <p class="title">{{ product.name }}</p> 
    <p class="price">{{ product.price | currency }}</p> 
    <p class="date">{{ product.pubdate | date }}</p> 
  </div> 
</div>

就能把

[ 
  { 
    name: 'The Book of Trees', 
    price: 19, 
    pubdate: new Date('2014', '03', '08'), 
    cover: 'img/the-book-of-trees.jpg' 
  }, 
  { 
    name: 'Program or be Programmed', 
    price: 8, 
    pubdate: new Date('2013', '08', '01'), 
    cover: 'img/program-or-be-programmed.jpg' 
  } 
]

这样的数组给刷进去。

directives(自定义标签)

ng-app,ng-controllerng-repeat, ng-src, ng-click...What can we generalize about directives? Directives bind behavior to HTML elements. When the app runs, AngularJS walks through each HTML element looking for directives. 

 $scope.plusOne = function(index){
        $scope.products[index].likes += 1;
 }
<p class="likes" ng-click="plusOne($index)">

做完绑定事件以后就出现了喜闻乐见的Congratulations!

  1. A user visits the AngularJS app.
  2. The view presents the app's data through the use of expressionsfilters, and directives. Directives bind new behavior HTML elements.
  3. A user clicks an element in the view. If the element has a directive, AngularJS runs the function.
  4. The function in the controller updates the state of the data.
  5. The view automatically changes and displays the updated data. The page doesn't need to reload at any point.

这张图倒是挺抢眼的:

ng-repeat 的用法:

<div ng-repeat="product in products">
  <img ng-src="{{ product.cover }}">
  <p class="title">{{ product.name }}</p>
</div>

这里很有趣的是product in products 的语法,其实controller中只定义了products,就去掉s写xxx in xxxs就行,

后面如果要用info模板,<app-info info="app"></app-info>

这个模板的命名就是appInfo用“-”拆开来,这个驼峰式也是Angular内约定俗成的, 它的定义方法就是下面一节的app.directive("appInfo"),function{...

Restrict

  • A 用于元素的 Attribute,这是默认值
  • E 用于元素的名称 (The 'E' means it will be used as a new HTML element.)
  • C 用于 CSS 中的 class

自定义一段html模板嵌入到index.html

  app.directive('appInfo', function() { 
  return { 
    restrict: 'E', 
    scope: { 
      info: '=' 
//
scope specifies pass information into this directive through an attribute named info
//The '=' tells the directive to look for an attribute named info in the <app-info> }, templateUrl:
'js/directives/appInfo.html' }; });

就像ui.framework的updateView一样,引用方便简单:<app-info info="move"></app-info> 

模板内部只需要html片段(含ng directive自定义标签和插值变量)。

当定义的directive方法带有传入的参数时:

app.directive('installApp', function() { 
  return { 
    restrict: 'E', 
    scope: { 
    }, 
    templateUrl: 'js/directives/installApp.html' ,
    link: function(scope, element, attrs) { 
      scope.buttonText = "Install", 
      scope.installed = false, //设了标识flag来切换两种按钮文字

      scope.download = function() { 
        element.toggleClass('btn-active'); //加上hover效果
        if(scope.installed) { 
          scope.buttonText = "Install"; 
          scope.installed = false; //改变标识flag的值
        } else { 
          scope.buttonText = "Uninstall"; 
          scope.installed = true; //改变标识flag的值
        } 
      };
        },
  };
});

这些参数是Angular处理传入的,就像ajax请求的回调函数,可以选择接收或者不接收。

 服务 Services

 AngularJS's built-in $http 封装后的用法是:

app.factory('forecast', ['$http', function($http) { 
  return $http.get('https://s3.amazonaws.com/codecademy-content/courses/ltp4/forecast-api/forecast.json') 
            .success(function(data) { 
              return data; 
            }) 
            .error(function(err) { 
              return err; 
            }); 
}]);

controller在接收service对象的时候也是可选参数。通常只需要一个$scape,现在传入一个名为forecast的服务:

app.controller('MainController', ['$scope', function($scope,'forecast') {
  //上面传入的forecast就是在单独的service文件中定义的服务名,注意要用字符串
}]);

目标:Display a day's four pieces of data. Use the date filter to format the datetime.

注意一个插值变量的写法 {{ day.datetime | date }}

前面是数据,后面是类型。

迁移 Routing

有过实战经验就知道routing是做应用时很重要的一环,我们公司搞了个坑死爹的State Machine来代参照和替代app.route,每次牵着这二货走道都很费劲。

在angular中,用ng-view(div写在head里面即可)引入routeProvider

app.js中初始化module后配置:

app.config(function ($routeProvider) { 
  $routeProvider 
    .when('/', { 
      controller: 'HomeController', 
      templateUrl: 'views/home.html' 
   }).when('/photos/:id', { controller: 'PhotoController', templateUrl: 'views/photo.html'
   }).otherwise({ redirectTo:
'/' }); });

 上面的代码意思是'/'的时候map html模板到controller

What did we just do?

  1. In app.js, we mapped a URL toPhotoController and photo.html. We added a variable part named id to the URL, like this: /photos/:id.
  2. In PhotoController, we used Angular's$routeParams to retrieve id from the URL by using $routeParams.id. Notice that we injected both $routeParams and the photos service into thePhotoController dependency array to make them available to use inside the controller.
  3. Then to fetch an individual photo, we first used the photos service to fetch the array of photos from the server, and then used$routeParams.id to access the specific photo by its index.
  4. As before, any properties attached to$scope become available to use in the view. This means in photo.html, we can display the photo's detail using expressions as done before.

Notice that when you click on links, the app doesn't do a full reload. Only the part of the view specified by <div ng-view></div> changes.

 

我喜欢这个logo,还想右键保存呢,结果人家是图标字体化的before。。。

<span class="cc-achievement cc-achievement--code-achievement"></span> 
 .cc-achievement{
  font-size: 120px;
  font-family: 'cc-achievement';
 }
.cc-achievement--code-achievement:before {
    content: "e62f";
}

好吧,个人网站上建一个子页做自定义demo去。

延伸阅读 学习资料合集

原文地址:https://www.cnblogs.com/haimingpro/p/5545711.html