简体   繁体   中英

Running JavaScript code from a file in AngularJS directive

I've made a directive in AngularJS for my footer section in a website that I load on every page. Inside, I've added some jQuery code that needs to get run once the page is loaded - that was the only solution I could think of for doing that. Here's an example of how it looks:

app.directive('footer', function () {
    return {
        restrict: 'A',
        replace: true,
        scope: {user: '='}, 
        templateUrl: "PATH_TO_HTML_FILE",
        controller: ['$scope', '$filter', function ($scope, $filter) {
            // Some random jQuery goes here, for example:
            $('.search-nav > a').on('click', function(){
                $('.search-drop-down').slideDown();
            });

            // Close Search form
            function closeSearchField() {
                $('.search-drop-down').slideUp();
            }
        }]
    };
});

I'm not sure if that's the best way to do it but what I want to do now is get this jQuery code in the controller out in a separate file. The reason: the front-enders that we work with have no idea what AngularJS is not even to mention directive, etc. so I just want to have a separate file with all the jQuery code that gets run on page load that they can edit if needed. Once the directive itself gets loaded, I would just like to get the contect of the file and run it in the body of the controller up above. Any ideas on how to do that? Or even a better solution to the whole problem?

You can define the controller in another file and just reference it in the directive by name:

Controller

app.controller('footerCtrl', footerCtrl);

//You are not actually using it in the controller, so you can remove it if you don't need it
footerCtrl.$inject = ['$scope', '$filter'];

function footerCtrl($scope, $filter){
    // Some random jQuery goes here, for example:
            $('.search-nav > a').on('click', function(){
                $('.search-drop-down').slideDown();
            });

            // Close Search form
            function closeSearchField() {
                $('.search-drop-down').slideUp();
            }
}

Directive

app.directive('footer', function () {
    return {
        restrict: 'A',
        replace: true,
        scope: {user: '='}, 
        templateUrl: "PATH_TO_HTML_FILE",
        controller: 'footerCtrl'
});

You can also get rid of this code entirely and just use a css class for the animation, using ng-class to add/remove the class when clicking the link

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