所以我有以下模板:
<div class="book-thumbs">
<div class="book-pic" ng-repeat="img in book.images">
<img ng-src="{{img}}" ng-click="vm.setImage(img)">
</div>
</div>
在控制器中我试图调用setImage(),但是我收到一个错误:$ scope未定义。
class BookController {
constructor($scope, $stateParams, $http) {
this.name = 'book';
$scope.bookId = $stateParams.bookId;
this.getBookInfo($http, $stateParams, $scope);
}
getBookInfo($http, $stateParams, $scope) {
$http.get('books/' + $stateParams.bookId + '.json').success(function(data) {
$scope.book = data;
$scope.mainImageUrl = data.images[0];
});
}
setImage(imageUrl) {
$scope.mainImageUrl = imageUrl;
}
}
BookController.$inject = ['$scope', '$stateParams', '$http'];
export default BookController;
我该如何解决?如果我尝试在setImage($ scope,img)中添加$ scope作为参数,则不会发生任何变化。谢谢
答案 0 :(得分:2)
使用构造函数中的this
变量更改访问方式并在控制器中分配依赖项。
Class BookController {
constructor($scope, $stateParams, $http) {
this.name = 'book';
//Add
this.$scope = $scope;
this.$stateParams = $stateParams;
this.$http = $http;
this.$scope.bookId = $stateParams.bookId;
this.getBookInfo();
}
getBookInfo() {
var that = this;
this.$http.get('books/' + this.$stateParams.bookId + '.json').success(function(data) {
that.$scope.book = data;
that.$scope.mainImageUrl = data.images[0];
});
}
setImage(imageUrl) {
this.$scope.mainImageUrl = imageUrl;
}
}
BookController.$inject = ['$scope', '$stateParams', '$http'];
export default BookController;
答案 1 :(得分:1)
试试这个你的JS文件:
"use strict";
var BookController = (function () {
function BookController($scope, $stateParams, $http) {
this.$scope = $scope;
this.$stateParams = $stateParams;
this.$http = $http;
this.name = "";
this.name = 'book';
$scope.bookId = $stateParams.bookId;
this.getBookInfo($http, $stateParams, $scope);
}
BookController.prototype.getBookInfo = function ($http, $stateParams, $scope) {
$http.get('books/' + $stateParams.bookId + '.json').success(function (data) {
$scope.book = data;
$scope.mainImageUrl = data.images[0];
});
};
BookController.prototype.setImage = function (imageUrl) {
this.$scope.mainImageUrl = imageUrl;
};
return BookController;
}());
BookController.$inject = ['$scope', '$stateParams', '$http'];
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = BookController;