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

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

本文关键字:存储 错误 控制器 scope 原型 工厂 方法      更新时间:2023-09-26

我真的有一个奇怪的问题,我真的不知道为什么这发生在我的头上。

--------- <工厂strong>

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 );
  }

--------- <控制器strong>

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中带有ng-click的goNext()的图标时,我得到错误消息,如果我这样做,函数不工作。

$scope.goNext = carousel.goNext;

goNext()不能在其作用域之外访问或触发。

然而,这工作得很好。

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

用$scope映射工厂的方法和公共变量的最佳实践是什么?

您正在丢失this上下文,使其:

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

goNext函数中,this不再是一个Carousel实例。它是控制器的一个实例。

检查此提琴:http://jsfiddle.net/vb0dnrkf/

最好这样做

当AngularJS正在创建作用域时,carousel变量实例还没有创建,所以你的$scope。goNext初始化为undefined

$scope.goNext = carousel.goNext;

但是当你点击图标,AngularJS调用回调,对象被创建,所以你可以调用那个函数