工厂原型中方法的奇怪错误,存储在控制器的 $scope 中

Weird error on method in prototype from factory, stored in $scope in controller

我遇到了一个很奇怪的问题,我真的想不通为什么会出现这种情况。

------------ 工厂

angular.module('myApp').factory('f_carousel', f_carousel);
f_carousel.$inject = ['$rootScope'];

function f_carousel($rootScope){

    // ---
    // Class ( Constructor )
    // ---

    function Carousel( totalSections ) {
        this.currentSection= 0;
        // All the initial variable for the constructor.
    }

    // ---
    // STATIC METHODS.
    // ---

    Carousel.load = function( totalSections ) {
        var carousel = new Carousel( totalSections );
        return( carousel );
    };

    // ---
    // INSTANCE METHODS.
    // ---

    Carousel.prototype = {

        // -------------
        // Public Methods
        // -------------

        // Click Event for the Next btn
        goNext: function goNext() {

            this.currentSection++;
            this.updateBtnVisibility();

        },
        // all other public & private methods below.
     }
     return ( Carousel );
  }

------------ 控制器

app.controller('aboutMeCtrl', aboutMeCtrl);
    aboutMeCtrl.$inject = ['$scope', 'f_carousel'];

    function aboutMeCtrl($scope, f_carousel){
        var carousel = f_carousel.load(3);
        $scope.currentSection = function(){
            return carousel.currentSection;
        };

        //This Works Fine.
        $scope.goNext = function(){
            carousel.goNext();
        };


        //This Doesnt Work.
        $scope.goNext = carousel.goNext;



    }

------------ 查看

<div class="m-slider__UI-arrow__icon" ng-click="goNext()"> Icon </div>

当我在 html 中单击具有 goNext() 和 ng-click 的图标时,我收到错误消息并且该功能不起作用如果我这样做。

$scope.goNext = carousel.goNext;

goNext() 无法在其范围之外访问或触发。

不过这很好用。

$scope.goNext = function(){
     carousel.goNext();
};

What is the best practice to map between methods and public variables from factory with $scope??

虽然 AngularJS 正在创建作用域,但轮播变量实例尚未创建,因此您的 $scope.goNext 被初始化为 undefined

$scope.goNext = carousel.goNext;

但是当您单击图标并且 AngularJS 调用回调时,会创建对象以便您能够调用该函数。

你正在失去 this 背景,让它成为:

$scope.goNext = carousel.goNext.bind( carousel );

内部 goNext 函数 this 不再是 Carousel 实例。它是您的控制器的一个实例。

检查此 fiddle:http://jsfiddle.net/vb0dnrkf/

最好这样做