简体   繁体   中英

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. 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):

// 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM