你有很多选择(我喜欢 Angular 的原因)。您可以在模块之外创建它们,然后在配置块中分配它们或使用angular.element()来获取其范围,如下所示:
HTML
<div ng-controller="MyCtrl" id='hi'>{{name | show}}! {{name2}}</div>
JS
//object 'something' with some method show that returns a formatted message
var something = (function () {
return {
show: function (s) {
return 'show ' + s;
}
}
})();
///controller
function MyCtrl($scope) {
$scope.name = 'Mitch';
$scope.name2 = '';
}
//module
angular.module('myApp', []).
value('a', something). //assignment of object to be used within module scope
filter('show', function (a) { //object something being used in this filter
return function (val) {
return a.show(val);
};
});
///Using the scope from a known element that uses a controller
$(function () {
var scope = angular.element('#hi').scope();
scope.$apply(function () {
//using the object again to change a value with the something object formatting the value.
scope.name2 = something.show('Mitch2');
});
});
上述代码的小提琴。
就个人而言,如果对象或函数已经在其他地方创建,以便在应用程序的其他非角度相关部分中使用,我会选择配置块。然后,共享实例会像服务一样传递给您的任何指令、过滤器(如本示例中)等。