Angular $资源不适用于Controller

时间:2017-04-12 08:24:29

标签: javascript angularjs angular-resource

过去几天一直在破坏我的大脑。非常感谢您帮助解决此问题

控制台上的错误消息 错误:[$ injector:unpr] http://errors.angularjs.org/1.6.4/ $ injector / unpr?p0 =%24resourceProvider%20%3C-%20%24resource%20%3C-%20menuFactory

  • 不使用$ resource的控制器正在另一个页面上工作 - AboutController
  • 使用$ resource的控制器在home.html - IndexController
  • 上不起作用
  • gulp传递一切

设置以确保角度依赖性到位 - 通过从bower组件中删除它们并从bower.json中删除依赖项,我确保所有版本的角度依赖项都已到位。使用-S开关

安装所有角度组件

"依赖":{     " bootstrap":" ~3.3.5",     " font-awesome":" ~4.4.0",     " angular-resource":" ^ 1.6.4",     " angular":" ^ 1.6.4",     " angular-ui-router":" ^ 0.4.2",     " angular-route":" ^ 1.6.4"   }

//app.js
'use strict';

angular.module('confusionApp', ['ui.router','ngResource'])

.config(function($stateProvider, $urlRouterProvider) {
    $stateProvider

        // route for the home page
        .state('app', {
            url:'/',
            views: {
                'header': {
                    templateUrl : 'views/header.html',
                },
                'content': {
                    templateUrl : 'views/home.html',
                    controller  : 'IndexController'
                },
                'footer': {
                    templateUrl : 'views/footer.html',
                }
            }

        })

        // route for the aboutus page
        .state('app.aboutus', {
            url:'aboutus',
            views: {
                'content@': {
                    templateUrl : 'views/aboutus.html',
                    controller  : 'AboutController'                  
                }
            }
        })

        // route for the contactus page
        .state('app.contactus', {
            url:'contactus',
            views: {
                'content@': {
                    templateUrl : 'views/contactus.html',
                    controller  : 'ContactController'                  
                }
            }
        })

        // route for the menu page
        .state('app.menu', {
            url: 'menu',
            views: {
                'content@': {
                    templateUrl : 'views/menu.html',
                    controller  : 'MenuController'
                }
            }
        })

        // route for the dishdetail page
        .state('app.dishdetails', {
            url: 'menu/:id',
            views: {
                'content@': {
                    templateUrl : 'views/dishdetail.html',
                    controller  : 'DishDetailController'
               }
            }
        });

    $urlRouterProvider.otherwise('/');
})
;




//controllers.js
'use strict';
angular.module('confusionApp')

.controller('MenuController', ['$scope', 'menuFactory', function ($scope, menuFactory) {

    $scope.tab = 1;
    $scope.filtText = '';
    $scope.showDetails = false;
    $scope.showMenu = true;
    $scope.message = "Loading ...";

    $scope.dishes = menuFactory.getDishes().query();

    $scope.select = function (setTab) {
        $scope.tab = setTab;

        if (setTab === 2) {
            $scope.filtText = "appetizer";
        } else if (setTab === 3) {
            $scope.filtText = "mains";
        } else if (setTab === 4) {
            $scope.filtText = "dessert";
        } else {
            $scope.filtText = "";
        }
    };

    $scope.isSelected = function (checkTab) {
        return ($scope.tab === checkTab);
    };

    $scope.toggleDetails = function () {
        $scope.showDetails = !$scope.showDetails;
    };

    }])

.controller('IndexController', ['$scope', 'menuFactory', 'corporateFactory', function ($scope, menuFactory, corporateFactory) {

    $scope.showDish = true;
    $scope.message = "Loading ...";
    //$scope.dish = menuFactory.getDishes().get({id:0});

    $scope.leader = corporateFactory.getLeader(3);
    $scope.promotion = menuFactory.getPromotion(0);
    }])


.controller('AboutController', ['$scope', 'corporateFactory', function ($scope, corporateFactory) {
    $scope.leaders = corporateFactory.getLeaders();
    }])

// services.js
'use strict';

angular.module('confusionApp')
.constant("baseURL", "http://localhost:3000/")

.service('menuFactory', ['$resource', 'baseURL', function ($resource, baseURL) {

    var promotions = [
        {
            _id: 0,
            name: 'Weekend Grand Buffet',
            image: 'images/buffet.png',
            label: 'New',
            price: '19.99',
            description: 'Featuring mouthwatering combinations with a choice of five different salads, six enticing appetizers, six main entrees and five choicest desserts. Free flowing bubbly and soft drinks. All for just $19.99 per person ',
            }

        ];

    this.getDishes = function () {
        return $resource(baseURL + "dishes/:id", null, {
            'update': {
                method: 'PUT'
            }
        });
    };

    this.getPromotion = function (index) {
        return promotions[index];
    };


        }])

.factory('corporateFactory', function () {

    var corpfac = {};

    var leadership = [
        {
            _id: 0,
            name: "Peter Pan",
            image: 'images/alberto.png',
            designation: "Chief Epicurious Officer",
            abbr: "CEO",
            description: "Our CEO, Peter, credits his hardworking East Asian immigrant parents who undertook the arduous journey to the shores of America with the intention of giving their children the best future. His mother's wizardy in the kitchen whipping up the tastiest dishes with whatever is available inexpensively at the supermarket, was his first inspiration to create the fusion cuisines for which The Frying Pan became well known. He brings his zeal for fusion cuisines to this restaurant, pioneering cross-cultural culinary connections."
            },
        {
            _id: 1,
            name: "Dhanasekaran Witherspoon",
            image: 'images/alberto.png',
            designation: "Chief Food Officer",
            abbr: "CFO",
            description: "Our CFO, Danny, as he is affectionately referred to by his colleagues, comes from a long established family tradition in farming and produce. His experiences growing up on a farm in the Australian outback gave him great appreciation for varieties of food sources. As he puts it in his own words, Everything that runs, wins, and everything that stays, pays!"
            },
        {
            _id: 2,
            name: "Agumbe Tang",
            image: 'images/alberto.png',
            designation: "Chief Taste Officer",
            abbr: "CTO",
            description: "Blessed with the most discerning gustatory sense, Agumbe, our CFO, personally ensures that every dish that we serve meets his exacting tastes. Our chefs dread the tongue lashing that ensues if their dish does not meet his exacting standards. He lives by his motto, You click only if you survive my lick."
            },
        {
            _id: 3,
            name: "Alberto Somayya",
            image: 'images/alberto.png',
            designation: "Executive Chef",
            abbr: "EC",
            description: "Award winning three-star Michelin chef with wide International experience having worked closely with whos-who in the culinary world, he specializes in creating mouthwatering Indo-Italian fusion experiences. He says, Put together the cuisines from the two craziest cultures, and you get a winning hit! Amma Mia!"
            }

        ];

    corpfac.getLeaders = function () {
        return leadership;
    };

    corpfac.getLeader = function (index) {
        return leadership[index];
    };

    return corpfac;

})

;

home.html做为        

    <!-- dish -->
    <div class="row row-content">
        <div class="col-xs-12 col-sm-3 col-sm-push-9">
            <p style="padding:20px;"></p>
            <h3 align=center>Our Lipsmacking Culinary Creations</h3>
        </div>

        <div class="col-xs-12 col-sm-9 col-sm-pull-3">
            <div ng-if="!showDish">
                <h3>{{message}}</h3>
            </div>


            <div class="media" ng-if="showDish">
                <div class="media-left media-middle">
                    <a href="#">
                        <img class="media-object img-thumbnail" ng-src={{dish.image}} alt={{dish.name}}>
                    </a>
                </div>
                <div class="media-body">
                    <h2 class="media-heading">{{dish.name}}
                        <span class="label label-danger">{{dish.label}}</span>
                        <span class="badge">{{dish.price | currency}}</span></h2>
                    <p>{{dish.description}}</p>
                </div>
            </div>
        </div>
    </div>

    <!-- promotion -->
    <div class="row row-content">
        <div class="col-xs-12 col-sm-3">
            <p style="padding:20px;"></p>
            <h3 align=center>This Month's Promotions</h3>
        </div>
        <div class="col-xs-12 col-sm-9">
            <div class="media">
                <div class="media-body">
                    <h2 class="media-heading">{{promotion.name}}
                        <span class="label label-danger">{{promotion.label}}</span>
                        <span class="badge">{{promotion.price | currency}}</span></h2>
                    <p>{{promotion.description}}</p>
                </div>
                <div class="media-left media-middle">
                    <a href="#">
                        <img class="media-object img-thumbnail" ng-src={{promotion.image}} alt={{promotion.name}}>
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- leader -->
    <div class="row row-content">
        <div class="col-xs-12 col-sm-3 col-sm-push-9">
            <p style="padding:20px;"></p>
            <h3 align=center>Meet our Culinary Specialists</h3>
        </div>
        <div class="col-xs-12 col-sm-9 col-sm-pull-3">
            <div class="media">
                <div class="media-left media-middle">
                    <a href="#">
                        <img class="media-object img-thumbnail" ng-src={{leader.image}} alt={{leader.name}}>
                    </a>
                </div>
                <div class="media-body">
                    <h2 class="media-heading">{{leader.name}}
                        <small>{{leader.designation}}</small></h2>
                    <p>{{leader.description}}</p>
                </div>
            </div>
        </div>
    </div>
</div>

gulpfile.js

var gulp = require('gulp'), 
    minifycss = require('gulp-minify-css'),
    jshint = require('gulp-jshint'),
    stylish = require('jshint-stylish'),
    uglify = require('gulp-uglify'),
    usemin = require('gulp-usemin'),
    imagemin = require('gulp-imagemin'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    notify = require('gulp-notify'),
    cache = require('gulp-cache'),
    changed = require('gulp-changed'),
    rev = require('gulp-rev'),
    browserSync = require('browser-sync'),
    ngannotate = require('gulp-ng-annotate'),
    del = require('del'),
    cleanCSS = require('gulp-clean-css');



gulp.task('jshint', function () {
    return gulp.src('app/scripts/**/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter(stylish));
});

// Clean
gulp.task('clean', function () {
    return del(['dist']);
    return del(['./json-server/public']);
});

// Default task
gulp.task('default', ['clean'], function () {
    gulp.start('usemin', 'imagemin', 'copyfonts');
});

gulp.task('usemin',['jshint'], function () {
  return gulp.src('./app/**/*.html')
      .pipe(usemin({
        css:[minifycss(),rev()],
        js: [ngannotate(),uglify(),rev()]
      }))
      .pipe(gulp.dest('dist/'));

});

// Images
gulp.task('imagemin', function () {
    return del(['dist/images']), gulp.src('./app/images/**/*')
        .pipe(cache(imagemin({
            optimizationLevel: 3,
            progressive: true,
            interlaced: true
        })))
        .pipe(gulp.dest('dist/images'))
        .pipe(notify({
            message: 'Images task complete'
        }));
});

gulp.task('copyfonts', ['clean'], function () {
    gulp.src('./bower_components/font-awesome/fonts/**/*.{ttf,woff,eof,svg}*')
        .pipe(gulp.dest('./dist/fonts'));
    gulp.src('./bower_components/bootstrap/dist/fonts/**/*.{ttf,woff,eof,svg}*')
        .pipe(gulp.dest('./dist/fonts'));
});

// Watch
gulp.task('watch', ['browser-sync'], function () {
    // Watch .js files
    gulp.watch('{app/scripts/**/*.js,app/styles/**/*.css,app/**/*.html}', ['usemin']);
    // Watch image files
    gulp.watch('app/images/**/*', ['imagemin']);

});

gulp.task('browser-sync', ['default'], function () {
    var files = [
      'app/**/*.html',
      'app/styles/**/*.css',
      'app/images/**/*.png',
      'app/scripts/**/*.js',
      'dist/**/*'
   ];

    browserSync.init(files, {
        server: {
            baseDir: "dist",
            index: "index.html"
        }
    });
    // Watch any files in dist/, reload on change
    gulp.watch(['dist/**']).on('change', browserSync.reload);
});

1 个答案:

答案 0 :(得分:1)

您在网址上指定了一个参数:id。但是,您传递的是null,请更正服务代码:

// services.js

'use strict';

angular.module('confusionApp')
.constant("baseURL", "http://localhost:3000/")

.service('menuFactory', ['$resource', 'baseURL', function ($resource, baseURL) {

    var promotions = [
        {
            _id: 0,
            name: 'Weekend Grand Buffet',
            image: 'images/buffet.png',
            label: 'New',
            price: '19.99',
            description: 'Featuring mouthwatering combinations with a choice of five different salads, six enticing appetizers, six main entrees and five choicest desserts. Free flowing bubbly and soft drinks. All for just $19.99 per person ',
            }

        ];

    this.getDishes = function () {
        return $resource(baseURL + "dishes/:id", { id: '@id' }, {
            'update': {
                method: 'PUT'
            }
        });
    };

    this.getPromotion = function (index) {
        return promotions[index];
    };


        }])

.factory('corporateFactory', function () {

    var corpfac = {};

    var leadership = [
        {
            _id: 0,
            name: "Peter Pan",
            image: 'images/alberto.png',
            designation: "Chief Epicurious Officer",
            abbr: "CEO",
            description: "Our CEO, Peter, credits his hardworking East Asian immigrant parents who undertook the arduous journey to the shores of America with the intention of giving their children the best future. His mother's wizardy in the kitchen whipping up the tastiest dishes with whatever is available inexpensively at the supermarket, was his first inspiration to create the fusion cuisines for which The Frying Pan became well known. He brings his zeal for fusion cuisines to this restaurant, pioneering cross-cultural culinary connections."
            },
        {
            _id: 1,
            name: "Dhanasekaran Witherspoon",
            image: 'images/alberto.png',
            designation: "Chief Food Officer",
            abbr: "CFO",
            description: "Our CFO, Danny, as he is affectionately referred to by his colleagues, comes from a long established family tradition in farming and produce. His experiences growing up on a farm in the Australian outback gave him great appreciation for varieties of food sources. As he puts it in his own words, Everything that runs, wins, and everything that stays, pays!"
            },
        {
            _id: 2,
            name: "Agumbe Tang",
            image: 'images/alberto.png',
            designation: "Chief Taste Officer",
            abbr: "CTO",
            description: "Blessed with the most discerning gustatory sense, Agumbe, our CFO, personally ensures that every dish that we serve meets his exacting tastes. Our chefs dread the tongue lashing that ensues if their dish does not meet his exacting standards. He lives by his motto, You click only if you survive my lick."
            },
        {
            _id: 3,
            name: "Alberto Somayya",
            image: 'images/alberto.png',
            designation: "Executive Chef",
            abbr: "EC",
            description: "Award winning three-star Michelin chef with wide International experience having worked closely with whos-who in the culinary world, he specializes in creating mouthwatering Indo-Italian fusion experiences. He says, Put together the cuisines from the two craziest cultures, and you get a winning hit! Amma Mia!"
            }

        ];

    corpfac.getLeaders = function () {
        return leadership;
    };

    corpfac.getLeader = function (index) {
        return leadership[index];
    };

    return corpfac;

});