Angular not defined

时间:2015-05-01 作者:Shahibur

我的网站上有这段代码,我不知道为什么角度没有定义,jquery也没有定义。我对web开发相当陌生,所以我不知道如何使用编码才能使其正常工作。

角度代码如下:

var app = angular.module(\'takeawaygrid\',[\'ngSanitize\',\'angularUtils.directives.dirPagination\',\'ui.bootstrap\' , \'ngProgress\' ,\'mgcrea.ngStrap\',\'ngAnimate\' ]);

app.filter(\'dashed\', function () {
        return function (text) {                
            var str = text.replace("\'", "").replace(/\\s+/g, \'-\');
            return str.toLowerCase();
        };
});


app.filter(\'html\',function($sce){
    return function(input){
        return $sce.trustAsHtml(input);
    }
});



app.filter(\'flatt\',function(){
    return function(input){
        var price = 0;
        angular.forEach(input, function(obj , index){
            price = parseFloat(price) + parseFloat(obj);
        });

        return price;


    }
});




app.controller(\'GridController\',function($scope , $http ,$timeout, ngProgress ,$alert){

    if( angular.isDefined(takeaway_category) ){
        $scope.takeway_category = takeaway_category.data.category_name;
        $scope.spec_cat = takeaway_category.data.cat_all_info;

        $scope.symbol = takeaway_category.data.currency_symbol;

        $scope.per_page = parseInt( takeaway_category.per_page );

    }



    $scope.chnagePrice = function( $event , childId , childPrice , scope , final_price){

        if( !angular.isDefined(final_price)){
                final_price = 0;
        }

        var checkbox = $event.target;
        if( checkbox.checked == true){  

                final_price = parseFloat(childPrice) + parseFloat(final_price);

        }else{

            final_price =  parseFloat(final_price) - parseFloat(childPrice);
        }


        return parseFloat(final_price);

    }


    $scope.selectedChild = function($event , childPrice , childId , selected_child , scope ){
        var checkbox = $event.target;

        if( !angular.isDefined(selected_child)){
                selected_child = [];
        }

        if( checkbox.checked == true ){

            selected_child.push({
                \'child_product_id\':childId,
                \'child_product_price\': childPrice
            });

        }else{

            angular.forEach(selected_child , function(child , index){
                    if(child.child_product_id == childId ){
                        selected_child.splice(index,1);
                    }
            });          

        }

        return selected_child;
    }   




    $scope.addToCart = function( post_id, post_price , post_selected_child){

        ngProgress.start();

        $http({
            method: \'POST\',
            url: takeaway_category.url+\'?action=do_add_to_cart\' ,
            data: jQuery.param({ \'items\': post_selected_child }),
            headers : { \'Content-Type\': \'application/x-www-form-urlencoded\' }
        }).success(function(e){




            if( e.success == 1 ){



                jQuery(\'span.amount\').html(e.cart);

                    $http({

                        method: \'POST\',
                        url: takeaway_category.url+\'?action=show_mini_cart\',                            
                        headers : { \'Content-Type\': \'application/x-www-form-urlencoded\' }

                    }).success(function(r){

                        jQuery(\'#mini-cart\').html(r); 
                        // jQuery(\'.header-top-bar .cart-contents\').addClass(\'redbg\');
                        // jQuery(\'#mini-cart\').slideDown(250);

                        jQuery(\'html, body\').animate({ scrollTop: 0 }, 500);

                    });


            } 




            $timeout(ngProgress.complete(), 800);
        });

    }




    $scope.addToCartSimple = function(post_id){


        $scope.showLoader = true;


        ngProgress.start();


        $http({
            method: \'POST\',
            url: takeaway_category.url+\'?action=do_add_to_cart_simple\',
            data: jQuery.param({ \'id\': post_id }),
            headers : { \'Content-Type\': \'application/x-www-form-urlencoded\' }
        }).success(function(e){                 




            if( e.success == 1 ){

            //  $alert({ content: e.message, placement: \'top\', type: \'material\', show: true });

                jQuery(\'span.amount\').html(e.cart);

                    $http({

                        method: \'POST\',
                        url: takeaway_category.url+\'?action=show_mini_cart\',                            
                        headers : { \'Content-Type\': \'application/x-www-form-urlencoded\' }

                    }).success(function(r){

                        jQuery(\'#mini-cart\').html(r);
                        jQuery(\'html, body\').animate({ scrollTop: 0 }, 500);

                        // jQuery(\'.header-top-bar .cart-contents\').addClass(\'redbg\');
                        // jQuery(\'#mini-cart\').slideDown(250);

                    });


            } 


            $timeout(ngProgress.complete(), 1000);

            $scope.showLoader = false;
        });

    }














        if( angular.isDefined(\'takeaway_category\') ){

            // $scope.formOption = [];
            // $scope.priceOption = [];

            // $scope.options = takeaway_category.option;

            // $scope.main_price = takeaway_category.main_price;
        }




        $scope.addOption = function( option , id , formOption , new_price  ){

                    var found = jQuery.inArray(option, formOption );
                    if (found >= 0) {
                        // Element was found, remove it.



                        //new_price = parseFloat(new_price) - parseFloat(option.price);




                        // new_price.splice(found ,1);                        
                        formOption.splice(found, 1);
                        new_price[0] = parseFloat(new_price[0]) - parseFloat(option.price);     


                    } else {
                        // Element was not found, add it.

                       // var price = 0;
                       // angular.forEach(new_price , function(obj, index)){

                       //      price = parseFloat(price) + parseFloat(obj);
                       // }
                       // price = parseFloat(price) + parseFloat(option.price);


                        // new_pricep[0] = option.price;

                        new_price[0] = parseFloat(new_price[0]) + parseFloat(option.price);   

                        formOption.push(option);
                    }

        }





        $scope.addSelectOption = function(option , id , selectedOption , formOption , price ){

                    if( formOption.length > 0){

                        angular.forEach( formOption , function(obj , index){

                                    if( obj.id == option.id){

                                        price[0] = parseFloat(price[0]) - parseFloat(obj.price);  
                                        formOption.splice(index, 1);                                    
                                        return;
                                    }
                        });

                        if( option.variation == \'yes\' ){
                            selectedOption.variation = \'yes\';
                        }

                        if( selectedOption != null){


                            if( price[0] == null){
                                price[0] = \'0\';
                            }

                            price[0] = parseFloat(price[0]) + parseFloat(selectedOption.price);  

                            formOption.push(selectedOption);
                        }


                    }else{

                        if( price[0] == null ){
                            price[0] = \'0\';
                        }

                        price[0] = parseFloat(price[0]) + parseFloat(selectedOption.price);  



                        formOption.push(selectedOption);
                    }
        }

        // $scope.option.selectedOption = $scope.options[1];



        function check_for_variation(options){

            angular.forEach(options , function(obj , index ){
                if(obj.variation == \'yes\'){

                    return true;
                }
            });
            return false;
        }





      $scope.doAddtoCartGrid = function( formOption , price_array , id ){

            // var quantity = 1;
        var quantity1 = angular.element(\'.p-\'+id).val();

        console.log(quantity1);


            var price = 0;

            angular.forEach( price_array , function(obj , index){
                price = parseFloat(price) + parseFloat(obj);
            });



            $scope.showLoader = true;




            $http({
                method: \'POST\',
                url: takeaway_category.url+\'?action=do_cart_new\',
                data: jQuery.param({ \'quantity\' : quantity1 , \'price\':price , \'option\':formOption , \'product_id\':id  }),
                headers : { \'Content-Type\': \'application/x-www-form-urlencoded\' }
            }).success(function(e){


                if( e.success == 1 ){



                    jQuery(\'span.amount\').html(e.cart);

                        $http({

                            method: \'POST\',
                            url: takeaway_category.url+\'?action=show_mini_cart\',                            
                            headers : { \'Content-Type\': \'application/x-www-form-urlencoded\' }

                        }).success(function(r){

                            jQuery(\'#mini-cart\').html(r); 
                            jQuery(\'html, body\').animate({ scrollTop: 0 }, 500);
                            //jQuery(location.reload(true));

                            // $location.url($location.path());

                         //     var currentPageTemplate = $route.current.templateUrl;
                            // $templateCache.remove(currentPageTemplate);
                            // $route.reload();

                        });


                } 





                $scope.showLoader = false;
            });


      }




});
/***食物选项*/

var food = angular.module(\'dyCart\',[]);


food.controller(\'dyController\',[\'$scope\',\'$http\', function($scope , $http ){





    if( angular.isDefined(\'takeaway_category\') ){

        $scope.formOption = [];
        $scope.priceOption = [];

        $scope.options = takeaway_category.option;

        $scope.main_price = takeaway_category.main_price;
    }




    $scope.addOption = function(option , id){

                var found = jQuery.inArray(option, $scope.formOption );
                if (found >= 0) {
                    // Element was found, remove it.
                    $scope.formOption.splice(found, 1);

                } else {
                    // Element was not found, add it.
                    $scope.formOption.push(option);
                }                       
    }





        $scope.addSelectOption = function(option , id , selectedOption ){

                    if( $scope.formOption.length > 0){

                        angular.forEach($scope.formOption , function(obj , index){

                                    if( obj.id == option.id){
                                        $scope.formOption.splice(index, 1);                                 
                                        return;
                                    }
                        });

                        if( option.variation == \'yes\' ){
                            selectedOption.variation = \'yes\';
                        }

                        if( selectedOption != null)
                            $scope.formOption.push(selectedOption);


                    }else{
                         $scope.formOption.push(selectedOption);
                    }

        }




    if( $scope.main_price){

        $scope.price = parseFloat( $scope.main_price ); 

    }else{

        $scope.price = 0.0; 

    }




    $scope.$watchCollection(
        "formOption",
        function( newValue, oldValue ){                     

            if( $scope.main_price){
                $scope.price = parseFloat( $scope.main_price );     
            }else{
                $scope.price = 0.0; 
            }

           angular.forEach(newValue , function(obj , index){

                if( obj.price != null ){
                    $scope.price = parseFloat($scope.price) + parseFloat(obj.price);

                }else{

                    if( obj.selectedOption.price ){
                        $scope.price = parseFloat($scope.price) + parseFloat(obj.selectedOption.price);
                    }

                }                               
           });

        }
    );



    function check_for_variation(options){

        angular.forEach(options , function(obj , index ){
            if(obj.variation == \'yes\'){

                return true;
            }
        });
        return false;
    }



  $scope.doAddtoCart = function(){



        // error check 
        var variation = check_for_variation($scope.options);

        // if( variation == false){
        //  alert(\'Please select Product variation \');
        // }




        var quantity = angular.element(\'.qty\').val();
        var product_id = angular.element(\'.food_product_id\').val();

        // console.log(\'algjalkd\');

        var totalPrice = $scope.price;
        var option = $scope.formOption;

        console.log(product_id);

            $http({
                method: \'POST\',
                url: takeaway_category.url+\'?action=do_cart_new\',
                data: jQuery.param({ \'quantity\' : quantity , \'price\':totalPrice , \'option\':option , \'product_id\':product_id  }),
                headers : { \'Content-Type\': \'application/x-www-form-urlencoded\' }
            }).success(function(e){

                // console.log(e);
                jQuery(\'#mini-cart\').html(e); 
                jQuery(\'html, body\').animate({ scrollTop: 0 }, 500);
            });                 


  }
}]);

jQuery代码是:

jQuery(document).ready(function($) {

/**
 * Variations form handling
 */
$(\'form.variations_form\')

    // On clicking the reset variation button
    .on( \'click\', \'.reset_variations\', function( event ) {

        //$(this).closest(\'form.variations_form\').find(\'.variations input:radio\').val(\'\').change();
        //$(this).find(\'.variations input:radio:checked\').each( function() {
            //$(this).checked = false;
        //}
        return false;
    } )

    // Upon changing an option
    .on( \'change\', \'.variations input:radio\', function( event ) {

        $variation_form = $(this).closest(\'form.variations_form\');
        $variation_form.find(\'input[name=variation_id]\').val(\'\').change();

        $variation_form
            .trigger( \'woocommerce_variation_radio_change\' )
            .trigger( \'check_variations\', [ \'\', false ] );

        $(this).blur();

        if( $().uniform && $.isFunction( $.uniform.update ) ) {
            $.uniform.update();
        }

    } )

    // Upon gaining focus
    .on( \'focusin\', \'.variations input:radio\', function( event ) {

        $variation_form = $(this).closest(\'form.variations_form\');

        $variation_form
            .trigger( \'woocommerce_variation_radio_focusin\' )
            .trigger( \'check_variations\', [ $(this).attr(\'name\'), true ] );

    } )

    // Check variations
    .on( \'check_variations\', function( event, exclude, focus ) {
        var all_set             = true;
        var any_set             = false;
        var showing_variation   = false;
        var current_settings    = {};
        var $variation_form     = $(this);
        var $reset_variations   = $variation_form.find(\'.reset_variations\');

        $variation_form.find(\'.variations input:radio:checked\').each( function() {

            if ( $(this).val().length == 0 ) {
                all_set = false;
            } else {
                any_set = true;
            }

            if ( exclude && $(this).attr(\'name\') == exclude ) {

                all_set = false;
                current_settings[$(this).attr(\'name\')] = \'\';

            } else {

                // Encode entities
                value = $(this).val()
                    .replace(/&/g, \'&\')
                    .replace(/"/g, \'"\')
                    .replace(/\'/g, "\'")
                    .replace(/</g, \'<\')
                    .replace(/>/g, \'>\');

                // Add to settings array
                current_settings[ $(this).attr(\'name\') ] = value;

            }

        });

        var product_id          = parseInt( $variation_form.attr( \'data-product_id\' ) );
        var all_variations      = window[ "product_variations_" + product_id ];

        // Fallback
        if ( ! all_variations )
            all_variations = window[ "product_variations" ];

        var matching_variations = find_matching_variations( all_variations, current_settings );

        if ( all_set ) {

            var variation = matching_variations.pop();

            if ( variation ) {
            if ( ! exclude ) {
                $variation_form.find(\'.single_variation_wrap\').slideDown(\'200\');
            }
                // Found - set ID
                $variation_form
                    .find(\'input[name=variation_id]\')
                    .val( variation.variation_id )
                    .change();

                $variation_form.trigger( \'found_variation\', [ variation ] );

            } else {

                // Nothing found - reset fields
                //$variation_form.find(\'.variations input:radio\').val(\'\');
                if ( ! exclude ) {
                $variation_form.find(\'.single_variation_wrap\').slideUp(\'200\');
            }
                if ( ! focus )
                    $variation_form.trigger( \'reset_image\' );

            }

        } else {

            $variation_form.trigger( \'update_variation_values\', [ matching_variations ] );

            if ( ! focus )
                $variation_form.trigger( \'reset_image\' );

            if ( ! exclude ) {
                $variation_form.find(\'.single_variation_wrap\').slideUp(\'200\');
            }

        }

        if ( any_set ) {

            if ( $reset_variations.css(\'visibility\') == \'hidden\' )
                $reset_variations.css(\'visibility\',\'visible\').hide().fadeIn();

        } else {

            $reset_variations.css(\'visibility\',\'hidden\');

        }

    } )

    // Reset product image
    .on( \'reset_image\', function( event ) {

        var $product        = $(this).closest( \'.product\' );
        var $product_img    = $product.find( \'div.images img:eq(0)\' );
        var $product_link   = $product.find( \'div.images a.zoom:eq(0)\' );
        var o_src           = $product_img.attr(\'data-o_src\');
        var o_title         = $product_img.attr(\'data-o_title\');
        var o_href          = $product_link.attr(\'data-o_href\');

        if ( o_src && o_href && o_title ) {
            $product_img
                .attr( \'src\', o_src )
                .attr( \'alt\', o_title )
                .attr( \'title\', o_title );
            $product_link
                .attr( \'href\', o_href );
        }

    } )

    // Disable option fields that are unavaiable for current set of attributes
    .on( \'update_variation_values\', function( event, variations ) {

        $variation_form = $(this).closest(\'form.variations_form\');

        // Loop through selects and disable/enable options based on selections
        $variation_form.find(\'.variations input:radio\').each(function( index, el ){

            current_attr_radio = $(el);

            // Disable all
            current_attr_radio.find(\'option:gt(0)\').attr(\'checked\', \'checked\');

            // Get name
            var current_attr_name   = current_attr_radio.attr(\'name\');

            // Loop through variations
            for ( num in variations ) {

                var attributes = variations[ num ].attributes;

                for ( attr_name in attributes ) {

                    var attr_val = attributes[ attr_name ];

                    if ( attr_name == current_attr_name ) {

                        if ( attr_val ) {

                            // Decode entities
                            attr_val = $("<div/>").html( attr_val ).text();

                            // Add slashes
                            attr_val = attr_val.replace(/\'/g, "\\\\\'");
                            attr_val = attr_val.replace(/"/g, "\\\\\\"");

                            // Compare the meercat
                            current_attr_radio.find(\'option[value="\' + attr_val + \'"]\').removeAttr(\'checked\');

                        } else {
                            current_attr_radio.find(\'option\').removeAttr(\'checked\');
                        }

                    }

                }

            }

        });

        // Custom event for when variations have been updated
        $variation_form.trigger(\'woocommerce_update_variation_values\');

    } )

    // Show single variation details (price, stock, image)
    .on( \'found_variation\', function( event, variation ) {
        var $variation_form = $(this);

        var $product        = $(this).closest( \'.product\' );
        var $product_img    = $product.find( \'div.images img:eq(0)\' );
        var $product_link   = $product.find( \'div.images a.zoom:eq(0)\' );

        var o_src           = $product_img.attr(\'data-o_src\');
        var o_title         = $product_img.attr(\'data-o_title\');
        var o_href          = $product_link.attr(\'data-o_href\');

        var variation_image = variation.image_src;
        var variation_link = variation.image_link;
        var variation_title = variation.image_title;

        $variation_form.find(\'.variations_button\').show();
        $variation_form.find(\'.single_variation\').html( variation.price_html + variation.availability_html );

        if ( ! o_src ) {
            o_src = ( ! $product_img.attr(\'src\') ) ? \'\' : $product_img.attr(\'src\');
            $product_img.attr(\'data-o_src\', o_src );
        }

        if ( ! o_href ) {
            o_href = ( ! $product_link.attr(\'href\') ) ? \'\' : $product_link.attr(\'href\');
            $product_link.attr(\'data-o_href\', o_href );
        }

        if ( ! o_title ) {
            o_title = ( ! $product_img.attr(\'title\') ) ? \'\' : $product_img.attr(\'title\');
            $product_img.attr(\'data-o_title\', o_title );
        }

        if ( variation_image && variation_image.length > 1 ) {
            $product_img
                .attr( \'src\', variation_image )
                .attr( \'alt\', variation_title )
                .attr( \'title\', variation_title );
            $product_link
                .attr( \'href\', variation_link );
        } else {
            $product_img
                .attr( \'src\', o_src )
                .attr( \'alt\', o_title )
                .attr( \'title\', o_title );
            $product_link
                .attr( \'href\', o_href );
        }

        var $single_variation_wrap = $variation_form.find(\'.single_variation_wrap\');

        if ( variation.sku )
             $product.find(\'.product_meta\').find(\'.sku\').text( variation.sku );
        else
             $product.find(\'.product_meta\').find(\'.sku\').text(\'\');

        $single_variation_wrap.find(\'.quantity\').show();

        if ( ! variation.is_in_stock && ! variation.backorders_allowed ) {
            $variation_form.find(\'.variations_button\').hide();
        }

        if ( variation.min_qty )
            $single_variation_wrap.find(\'input[name=quantity]\').attr( \'data-min\', variation.min_qty ).val( variation.min_qty );
        else
            $single_variation_wrap.find(\'input[name=quantity]\').removeAttr(\'data-min\');

        if ( variation.max_qty )
            $single_variation_wrap.find(\'input[name=quantity]\').attr(\'data-max\', variation.max_qty);
        else
            $single_variation_wrap.find(\'input[name=quantity]\').removeAttr(\'data-max\');

        if ( variation.is_sold_individually == \'yes\' ) {
            $single_variation_wrap.find(\'input[name=quantity]\').val(\'1\');
            $single_variation_wrap.find(\'.quantity\').hide();
        }

        $single_variation_wrap.slideDown(\'200\').trigger( \'show_variation\', [ variation ] );

    } );

/**
 * Initial states and loading
 */
$(\'form.variations_form .variations input:radio\').change();


/**
 * Helper functions for variations
 */

// Search for matching variations for given set of attributes
function find_matching_variations( product_variations, settings ) {
    var matching = [];

    for (var i = 0; i < product_variations.length; i++) {
        var variation = product_variations[i];
        var variation_id = variation.variation_id;

        if ( variations_match( variation.attributes, settings ) ) {
            matching.push(variation);
        }
    }
    return matching;
}
var count=0;
// Check if two arrays of attributes match
function variations_match( attrs1, attrs2 ) {
    var match = true;
    for ( attr_name in attrs1 ) {
        var val1="";
         var val2="";
        if(count>1)
        {
         val1 = String(attrs1[ attr_name ]).toLowerCase();
         val2 = String(attrs2[ attr_name ]).toLowerCase();
        }
        else
        {
          val1 =attrs1[ attr_name ];
         val2 = attrs2[ attr_name ];
         count++;
        }


        if ( val1 !== undefined && val2 !== undefined && val1.length != 0 && val2.length != 0 && val1 != val2 ) {
            match = false;
        }
    }
    return match;
}
函数isNumber(n){返回!isNaN(parseFloat(n))&isFinite(n);}};

在我的网站上不起作用的功能是向购物车添加产品选项。该网站是http://shahiburrahman.co.uk . 我认为,由于这些问题,这就是功能不起作用的原因,但我可能错了。

任何帮助或回应都将不胜感激。

沙希布尔

1 个回复
最合适的回答,由SO网友:Tobias 整理而成

您应该使用wp_enqueue_script 添加脚本。文档包含有关该函数的信息、应如何使用该函数以及一些有用的示例。

基本上,您需要向functions.php 文件:

function myextension_enqueue_scripts() {
    wp_enqueue_script(
        \'myextension-angular\',
        plugins_url( \'/assets/js/angular.min.js\' , __FILE__ ),
        // If you are working on a theme, not a plugin,
        // replace the above line with this:
        // get_stylesheet_directory_uri() . \'/assets/js/angular.min.js\',
        array( \'jquery\' )
    );
    wp_enqueue_script(
        \'myextension-angular-custom\',
        plugins_url( \'/assets/js/angular-custom.js\' , __FILE__ ),
        // If you are working on a theme, not a plugin,
        // replace the above line with this:
        // get_stylesheet_directory_uri() . \'/assets/js/angular-custom.js\',
        array( \'jquery\', \'myextension-angular\' )
    );
    wp_enqueue_script(
        \'myextension-add-to-cart-variation\',
        plugins_url( \'/assets/js/add-to-cart-variation.min.js\' , __FILE__ ),
        // If you are working on a theme, not a plugin,
        // replace the above line with this:
        // get_stylesheet_directory_uri() . \'/assets/js/add-to-cart-variation.min.js\',
        array( \'jquery\', \'myextension-angular\' )
    );
}

add_action( \'wp_enqueue_scripts\', \'myextension_enqueue_scripts\' );
Edit: 我以为文件angular-custom.js 包含angular,但是,我刚刚认识到您将代码拆分为两个文件,甚至不包括angular。我修改了代码以包含第三个文件,angular.min.js, 你需要download 并添加。

结束

相关推荐

显示特定类别的single.php的代码也覆盖了普通的single.php

我目前正在建立的网站上有两种不同的帖子类型——“press”和“blog”。我使用了以下代码,插入到我的子主题函数中。php文件,以获取使用“single press.php”模板的“press”帖子:add_filter( \'single_template\', function ( $single_template ) { $parent = \'7\'; $categories = get_categories( \'child_of=\' . $parent