我是angularJS的新手。
当我在angularJS指令中声明一个var或一个函数时,aFunction()和aVar属于哪个命名空间?
以这种方式声明它们是正确的还是我应该在它们前面加上,例如$ scope?
以下是代码段:
define(['aName'], function () {'use strict';
angular.module('aName').directive('aName', ['$compile', 'serviceName',
'$parse', '$window', '$document', function ($compile, serviceName, $parse,
myWindow, $document) { return {
...
function aFunction() { ... } //or should it be $scope.aFunction?
var aVar = function anotherFunction() { ... } //or should it be $scope.aVar?
...
};
}]);
});
答案 0 :(得分:1)
angularjs中的命名空间不是最强的部分。事情最终转移到一个名为angular
的对象。这里定义了几个可用于创建对象的函数,如module
。这对service names(我们依赖使用服务名称的依赖注入)或全局函数控制器特别有问题。
模块是一个逻辑组,例如,指令或控制器,但(不太确定)它不是隔离组件的方法。尝试a directive with the same name in two modules。
在本教程中,他们将控制器定义为全局函数:
function MainCtrl() {...}
而不是使用模块,至少不会污染全局命名空间。
app.controller('MainCtrl', function ($scope) {
angular.directive()返回一个DDO(指令定义对象),如:
app.directive('person', function () {
return {
restrict: 'E',
replace: true,
template: '<div class="person">Person name: {{ name }}</div>',
scope: {
name: '@'
}
};
});
您应该使用一组有限的属性(限制,替换,模板,templateUrl ......)。
有function aFunction() { ... }
没有多大意义。它甚至不是key:value
。
如果它是一个函数,它将一些逻辑封装在你的指令中但不必暴露给视图,你可以按如下方式进行:
app.directive('person', function () {
var f = function() {...};
return {
restrict: 'E',
replace: true,
template: '<div class="person">Person name: {{ name }}</div>',
link: function(...) {
/* and it becomes available */
f()
}
};
});
如果你不使用var
,它会尝试按照javascript范围规则将其解析为全局对象。
你的第二个例子var aVar = function anotherFunction() { ... }
是一个只在当前[javascript]范围内可用的函数,也就是说,你使用它的任何函数。例如:
link: function(...) {
/* and it becomes available */
f();
var g = function () {...};
g(); // only works in the scope of link();
}
如果您想要将此函数公开给视图,那么对于类似<div ng-click="fireFn()">
的内容,您可能应该在范围内使用它。在作用域中定义此函数的好地方是控制器或链接函数:
在控制器中,
app.controller('MainCtrl', function ($scope) {
$scope.name = 'World';
$scope.fireFn = function() {...}; // scope is the injected service. use the $
});
在链接器中:
link: function(scope) {
/* and it becomes available */
f();
var g = function () {...};
g(); // only works in the javascript scope (not the parameter!) of link();
scope.fireFn = function() {...}; // scope is the first parameter
}
关于隔离模块,将它们放在封闭处不会造成任何伤害:
(function () {
"use strict";
var mymodule = angular.module('mymodule', []);
}());