gpt4 book ai didi

javascript - Angular Material $mdDialog - 无法访问确认函数中的 'this' 项

转载 作者:行者123 更新时间:2023-11-30 20:55:22 25 4
gpt4 key购买 nike

我正在尝试使用 Angular Material $mdDialog 的确认功能来清除数组,然后将此数组记录到控制台,但访问“this”对象/数组/表达式/函数似乎存在问题在 $mdDialog 函数本身中,控制台显示任何引用的项目都是未定义的,即使之前在其他 Controller 函数中使用过也是如此。

$mdDialog 指令是否存在 controllerAs 语法问题?

-

Controller :

app.controller('notificationsController', function($scope, $state, $http, $document, $mdDialog, $filter, $timeout) {

this.selectedNotification = null;
this.notifications = [
{
title: 'Notification One',
description: 'Description...',
time: '2017-10-27T16:39:32+00:00',
importance: 'Low',
read: false
},

etc...

$scope.clearNotifications = function(ev) {
var confirm = $mdDialog.confirm()
.parent(angular.element('body'))
.clickOutsideToClose(true)
.title('Are you sure you want to clear all notifications?')
.textContent('This action cannot be undone.')
.ariaLabel('Confirm notifications list clearance')
.ok('Yes')
.cancel('No')
.targetEvent(ev)

$mdDialog.show(confirm).then(function() {
$scope.status = 'All notifications deleted';
console.log($scope.status);
this.notifications.length = 0;
console.log(this.notifications);
}, function() {
$scope.status = 'Notifications list not cleared';
console.log($scope.status);
})
}

最佳答案

this 在:

$mdDialog.show(confirm).then(function() {
...
this.notifications.length = 0; // <---- here
...
}, function() {
...
})

指的是 $mdDialog.show() 返回的 promise 的 promise 解析函数,如果你想访问你必须创建的 Controller 的 notifications 成员引用 Controller 的 this 的 var:

app.controller('notificationsController', function($scope, $state,           
$http, $document, $mdDialog, $filter, $timeout) {

var _this = this; // <--- Now _this is the controller
this.notifications = [
{
title: 'Notification One',
description: 'Description...',
time: '2017-10-27T16:39:32+00:00',
importance: 'Low',
read: false
},

etc...

$scope.clearNotifications = function(ev) {
...

$mdDialog.show(confirm).then(function() {
...
_this.notifications.length = 0; //<--- using _this and not this
...
}, function() {
...
})
}

关于javascript - Angular Material $mdDialog - 无法访问确认函数中的 'this' 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47718399/

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