Question

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; });
                        });
                    }
                }
            }
        ]);
Was it helpful?

Solution

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.

OTHER TIPS

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; });
        })
     };
}]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top