来自工厂的原型中的方法出现了奇怪的错误,存储在控制器的$scope中
Weird error on method in prototype from factory, stored in $scope in controller
我真的有一个奇怪的问题,我真的不知道为什么这发生在我的头上。
--------- <工厂strong>工厂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>控制器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调用回调,对象被创建,所以你可以调用那个函数
相关文章:
- Javascript:将数据存储在变量中.初级错误
- 如何在存储中插入时接收错误
- Azure Blob 存储 请求的资源错误中不存在访问控制允许源标头
- 从远程存储库中提取并得到:“解析错误:关键字'import'被保留”
- Blueimp jquery文件上传插件在上传100%后抛出错误到机架空间云存储
- 使用 vuejs 新的 vuex 存储得到意外的配置错误
- 为什么我的 ajax 调用不将数据存储在数据库中?没有 PHP 或控制台错误
- 错误:FS.Store.S3 您必须指定“存储桶”选项(meteor.js 和 s3)
- 如何将誓言令牌推送到本地存储或本地会话并监听存储事件?(SoundCloud Php/JS 错误解决方法)
- 存储为空或不是 dojo 中的对象错误
- ExtJs 4.2, 网格中继来自存储加载事件的事件导致未捕获的类型错误: 未定义不是一个函数
- 日期选取器存储错误值的问题
- HTML5 本地存储错误
- 本地存储错误 - NS_ERROR_FILE_CORRUPTED - 火狐
- Javascript本地存储错误
- JBoss的本地存储错误
- 奇怪的chrome存储错误
- 移动safari私人浏览本地存储错误,但没有代码调用它
- 编码器验证库在会话中存储错误
- 阵列推送时本地存储错误