AngularJS学习笔记(一)——一些基本知识

(一)Hello Angular

AngularJS学习笔记(一)——一些基本知识

index.html

<!DOCTYPE html>

<html ng-app>

  <head>

    <title>Test AngularJS</title>

    <meta charset="utf-8">

  </head>

  <body>

    <div ng-controller="HelloAngular">

      <p>{{greeting.text}},Angular</p>

    </div>

  </body>

  <script src="js/angular.min.js"></script>

  <script src="controller/HelloAngular.js"></script>

</html>

HelloAngular.js

function HelloAngular($scope) {

  $scope.greeting = {

    text: 'Hello'

  };

}

 

angular.min.js

这个文件在网上随便那里下个吧,比如新浪的前端库地址:http://lib.sinaapp.com/js/angular.js/angular-1.1.0/angular.min.js

min是压缩后的文件,在indexl中直接引入链接也可,但还是下载到本地方便呢

 

在浏览器打开index.hml,看看输出吧~

 

PS:上面的index.html中的使用ng-controller的方式存在一点点问题,就是快速刷新网页或者是很多数据的时候会有短暂的显示{{greeting.text}},我们可以通过如下的方式解决。

<p>{{greeting.text}},Angular</p>

把index.html中的上面那句换成

<p><span ng-bind="greeting.text"></span>,Angular</p>

在网页没加载好的情况下会显示“,Angular”,而不是“{{greeting.text}},Angular”

 

(二)错误的控制器使用方法

不要使用通用控制器,进行继承或调用等,每个控制器只负责一小部分的逻辑即可

如下的控制器和首页引用代码是不建议使用的样例:

HTML

<div ng-controller="CommonController">

  <div ng-controller="Controller1">

    <p>{{greeting.text}}, Angular</p>

    <button ng-click="test1()">Click1</button>

  </div>

  <div ng-controller="Controller2">

    <p>{{greeting.text}}, Angular</p>

    <button ng-click="test2()">Click2</button>

  </div>

  <button ng-click="common()">Common</button>

</div>

Controller

function CommonController($scope) {

  $scope.common = function() {

    alert("Common");

  };

}



function Controller1($scope) {

  $scope.greeing = {

    text: 'Hello1'

  };

  $scope.test1 = function() {

    alert("Test1");

  };

}



function Controller2($scope) {

  $scope.greeing = {

    text: 'Hello2'

  };

  $scope.test2 = function() {

    alert("Test2");

  };

}

虽然可以正常的工作,但是建议把公共的代码抽象成“服务”来实现。

 

(三)ng-model 的时时显示

<!DOCTYPE html>

<html ng-app>

  <head>

    <title>Test AngularJS</title>

    <meta charset="utf-8">

  </head>

  <body>

    <div>

      <input ng-model="qq" />

      <p>{{ qq }}</p>

    </div>

  </body>

  <script src="js/angular.min.js"></script>

</html>

AngularJS学习笔记(一)——一些基本知识

上面就是效果,输入什么下面就同步的显示什么


(四)ng-repeat

下面的代码片段是一个简单的循环

<div>

<ol>

  <li ng-repeat="name in names">

    {{name}} from {{department}}

  </li>

</ol>

</div>

 可以定义全局的rootScope,这是全局可用的

function CreetCtrl($scope, $rootScope) {

  $rootScope.department = 'Angular';

}



function ListCtrl ($scope) {

  $scope.names = ['David', 'Dong', 'Sellea'];

}

 

(五)路由,模块,依赖注入

(一)中的控制器定义的是全局变量,这样做是不好的,而且也不模块化

var helloModule = angular.module('HelloAngular', []);

helloModule.controller('helloNgCtrl', ['$scope', function($scope){

  $scope.greeting = {

    text: 'Hello'

  };

}]);

路由自带的也可以,不过使用angular-ui-router这个模块会更好

依赖注入的功能使得AngularJS可以方便的引入模块,在引入最小数量模块的同时实现功能

 

Hello World会写后,接下来学习些双向数据绑定什么的,这些概念都是第一次听说,AngularJS真是个蛮有趣的东西

 

你可能感兴趣的:(AngularJS)