首页 > 语言 > JavaScript > 正文

使用Angular.js开发的注意事项

2024-05-06 15:08:14
字体:
来源:转载
供稿:网友

前言

近期一直在玩Angularjs,不得不说,相对于Knockout,Angularjs这一MVVM框架更强大,也更复杂,各种教程网上到处都是,不过真正用到项目的时候会遇到各种坑。

一、ng-repeat

ng-repeat 用于标识某个 elem 需要重复输出,同时重复输出的内容需为唯一

<div ng-app="app" ng-controller="control">  <h3 ng-repeat="content in repeatContent">ng-repeat: {{ content }}</h3></div>
let app = angular.module("app", []);app.controller("control", ($scope) => {  // 输出李滨泓  $scope.repeatContent = ["李", "滨", "泓"];  // 下面存在两个“泓”,会报错  // $scope.repeatContent = ["李", "滨", "泓", "泓"];})

二、provider, service, factory 之间的关系

factory

factory 很像 service,不同之处在于,service 在 Angular 中是一个单例对象,即当需要使用 service 时,使用 new 关键字来创建一个(也仅此一个)service。而 factory 则是一个普通的函数,当需要用时,他也仅仅是一个普通函数的调用方式,它可以返回各种形式的数据,例如通过返回一个功能函数的集合对象来将供与使用。

定义:

let app = angular.module("app", []);// 这里可以注入 $http 等 Providerapp.factory("Today", () => {  let date = new Date();  return {    year: date.getFullYear(),    month: date.getMonth() + 1,    day: date.getDate()  };});

使用注入:

app.controller("control", (Today) => {  console.log(Today.year);  console.log(Today.month);  console.log(Today.day);});

service

service 在使用时是一个单例对象,同时也是一个 constructor,它的特点让它可以不返回任何东西,因为它使用 new 关键字新建,同时它可以用在 controller 之间的通讯与数据交互,因为 controller 在无用时其作用域链会被销毁(例如使用路由跳转到另一个页面,同时使用了另一个 controller)

定义:

let app = angular.module("app", []);// 这里可以注入 $http 等 Provider// 注意这里不可以使用 arrow function// arrow function 不能作为 constructorapp.service("Today", function() {  let date = new Date();  this.year = date.getFullYear();  this.month = date.getMonth() + 1;  this.day = date.getDate();});

使用注入:

app.controller("control", (Today) => {  console.log(Today.year);  console.log(Today.month);  console.log(Today.day);});

provider

provider 是 service 的底层创建方式,可以理解 provider 是一个可配置版的 service,我们可以在正式注入 provider 前对 provider 进行一些参数的配置。

定义:

let app = angular.module("app", []);// 这里可以注入 $http 等 Provider// 注意这里不可以使用 arrow function// arrow function 不能作为 constructorapp.provider("Today", function() {  this.date = new Date();  let self = this;  this.setDate = (year, month, day) => {    this.date = new Date(year, month - 1, day);  }  this.$get = () => {    return {      year: this.date.getFullYear(),      month: this.date.getMonth() + 1,      day: this.date.getDate()    };  };});            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选