gpt4 book ai didi

javascript - 如何通过 ng-click 将 $scope 传递给 Controller ​​?

转载 作者:行者123 更新时间:2023-11-28 18:32:25 25 4
gpt4 key购买 nike

所以我有以下模板:

 <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>

在 Controller 中,我尝试调用 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;

我该如何解决这个问题?如果我尝试将 $scope 添加为 setImage($scope, img) 中的参数,则不会发生任何变化。谢谢

最佳答案

使用构造函数中的 this 变量更改 Controller 中的访问和分配依赖项的方式。

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;

关于javascript - 如何通过 ng-click 将 $scope 传递给 Controller ​​?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37730114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com