我是Angular.js的新手。
I have an app which contains few tabs with different pages. Each page is maintained by different controller to manage its own data. My doubt is, how to use same functions across different pages (controllers). For example, fields of different pages would have same validation functions, formatting functions and many other util functions.1.如何维护不同控制器之间的通用功能?
2.如何将作为侦听器的公共函数绑定到绑定到不同页(由不同控制器管理)字段的事件,因为它们不共享范围?
谢谢。
发布于 2015-09-16 21:13:05
使用工厂或服务
要在不同控制器之间共享功能,可以使用工厂或服务。一个例子将更好地说明这一点。
控制器与工厂
这是角JS文档中的一个例子。工厂可以在注入功能的任何地方使用。
angular.
module('myServiceModule', []).
controller('MyController', ['$scope','notify', function ($scope, notify) {
$scope.callNotify = function(msg) {
notify(msg);
};
}]).
factory('notify', ['$window', function(win) {
var msgs = [];
return function(msg) {
msgs.push(msg);
if (msgs.length == 3) {
win.alert(msgs.join("\n"));
msgs = [];
}
};
}]);在控制器上的函数中,有一个notify注入,如果您愿意,可以在另一个控制器中调用它。
指令
您还应该看看指令,它们允许您编写自己的html标记或属性。它们可以在不同的页面上重用。
示例指令
这是实际的指令代码
app.directive('appInfo', function() {
return {
restrict: 'E',
scope: {
info: '='
},
templateUrl: 'js/directives/appInfo.html'
};
});restrict: E意味着它将用作一个元素,而不是一个属性。
scope列出了元素可用的不同作用域。
templateUrl链接到您存储html片段的位置。
以下是指令html片段
<img class="icon" ng-src="{{ info.icon }}">
<h2 class="title">{{ info.title }}</h2>
<p class="developer">{{ info.developer }}</p>
<p class="price">{{ info.price | currency }}</p>确保我们可以从作用域访问info
下面将指令作为标签放在我们的主html中,您可以将它放入索引页面或任何模板中,只要您愿意,多次都可以。
<div class="card">
<app-info info="move"></app-info>
</div>这是构建指令的基础,这个指令只有html和作用域,但是您可以制作更复杂的使用控制器的指令。
学习附加备注
花点时间阅读科德勒密 AngularJS教程,它们是免费的,最多只花两个晚上的工作时间。它们还解释了角JS的所有基础知识,如指令、控制器、服务等。
发布于 2015-09-16 21:10:21
这就是服务/工厂的作用。
它们提供了单例“类”,包含您希望在应用程序中共享的任何数据和功能。
例如:
app.factory('myService', function() {
return {
doSomethingCool: doSomethingCool
};
});
app.controller('myController', function(myService) {
myService.doSomethingCool();
});工厂和服务之间有一些细微的差别,所以您必须研究这些差异(这有点超出了这个问题的范围)。
https://stackoverflow.com/questions/32618713
复制相似问题