Angular JS 使用技巧

来源:互联网 发布:淘宝管控记录怎么上架 编辑:程序博客网 时间:2024/06/07 13:58

最近用Angular JS做为前端框架,本文记录一些使用过程中的技巧,只做用法的描述,不做过多原理上的讨论。

1 多个ng-app-id

Angular JS规定,一个页面中只能引入一个ng-app,这样比较不利于多人协作开发,有什么解决办法呢?就是引入ng-app-id。具体做法是,假设你要写一个article.js用来操作文章,就在该js最开始的地方加入下面一段代码

angular.element(document).ready(    function () {        var element = $("[ng-app-id=article]");        for (var i = 0; i < element.length; i++)            angular.bootstrap(element[i], ["article"]);    });

接下来,只需要在你的页面中,声明该ng-app-id,就可以使用article.js中的controller了。

div(ng-app-id="article")

这样,在同一个页面不相互嵌套的div中,就可以使用多个ng-app-id。

2 ng-app-id嵌套

假设这样一种情况。你在接收一个项目的时候,看到别人已经写了下面的代码(后面的代码省略):

div(ng-app-id="article")    ul       .       .       .

现在你需要在页面中嵌入广告,显然把广告相关的controller和service写到article.js中是很不恰当的。此时你会发现,加入advertise.js之后,原有的article.js里面的controller无法正常工作了。

div(ng-app-id="article")    ul        div(ng-app-id="advertise")                  .                  .                  .

此时为了同时使用两个js文件中的controller就陷入了两难境地。具体方法是,在advertise.js开头声明中注入article.js,这样只需要在页面中使用div(ng-app-id=”advertise”),就可以继续使用article.js中的controller了。

var advertise = angular.module('advertise', ['ngDialog', 'article', 'user']);

3 ng-repeat

ng-repeat相当好用,但是局限性也很强。我从数据库中取一系列数据的时候,想要剔除第一个,只拿后面的。这个功能在后台实现起来有点杀鸡焉用牛刀的感觉,其实ng-repeat是有这个功能的。

div.item(ng-repeat="x in photos.slice(1)")

这样你取出的x就直接是从第二个循环到最后一个。

除此之外,ng-repeat也可以用来实现类似于

for(i=0;i<n;i++)

的功能,只需要活用{{$index}}即可。这里有一点要格外注意:

"{{$index+1}}",得到"1","2","3"等等"{{$index}}+1",得到"0+1","1+1","2+1"等等

4 $on $emit $broadcast

这个是$scope经常用到的,用于各个scope之间的消息传递。一旦发生了某个时间,就通过$emit或者$broadcast来发出消息,再通过$on进行响应。

区别在于,$emit是向上级$scope发送消息,而$broadcast是向下级$scope发送消息。

举个栗子,像本文中第二部分,声明了下面的代码之后,advertise.js中的$scope就相当于是article.js中的$scope的下级。

var advertise = angular.module('advertise', ['ngDialog', 'article', 'user']);

这样在article.js的某个controller中$broadcast出的消息就可以在advertise.js中的controller通过$on触发某个事件。还是来个栗子

advertise.controller("manageAdvertise",function ($scope, $http, $location, $rootScope){    $scope.$on("messageSent", function () {        ...    });});
article.controller("manageArticle",function($scope, $http, $location, $rootScope){    $scope.updateArticle = function(){         $scope.$broadcast("messageSent");    }});

说明:
如有转载,务必在文章开头注明出处
http://blog.csdn.net/antony9118/article/details/53286302

0 0
原创粉丝点击