[英]ANgular Directives in a separate JS file?
I have this ngFocused directive working, but I'd like to put it into its own js file. 我有这个ngFocused指令在工作,但是我想将其放入自己的js文件中。 How would I wire that up?
我该如何接线呢?
var appObject = angular
.module('app', ['ngAnimate'])
.directive('ngFocused', [
function() {
var FOCUS_CLASS = "focused";
return {
restrict: 'A', //Attribute only
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
ctrl.$focused = false;
element.bind('focus', function(evt) {
element.addClass(FOCUS_CLASS);
scope.$apply(function() { ctrl.$focused = true; });
}).bind('blur', function(evt) {
element.removeClass(FOCUS_CLASS);
scope.$apply(function() { ctrl.$focused = false; });
});
}
}
}
]);
Just split them into two files. 只需将它们分成两个文件即可。 (And don't forget to reference the new file to your html file using the
<script>
tag): (并且不要忘记使用
<script>
标记将新文件引用到html文件中):
// file app.js
var appObject = angular.module('app', ['ngAnimate'])
// file ngFocused.js
appObject.directive('ngFocused', [ function() {
var FOCUS_CLASS = "focused";
return {
restrict: 'A', //Attribute only
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
ctrl.$focused = false;
element.bind('focus', function(evt) {
element.addClass(FOCUS_CLASS);
scope.$apply(function() { ctrl.$focused = true; });
}).bind('blur', function(evt) {
element.removeClass(FOCUS_CLASS);
scope.$apply(function() { ctrl.$focused = false; });
})
};
}]);
i like the IIFE approach. 我喜欢IIFE方法。 In your new file:
在您的新文件中:
(function(app) {
app.directive(....)
}(angular.module('app'));
That'll keep all your objects out of the global namespace. 这样可以将所有对象都保留在全局名称空间之外。 Be sure to reference your script defining your angular app before one's that reference it.
确保先引用定义角度应用程序的脚本,然后再引用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.