gpt4 book ai didi

javascript - Angularjs $scope 和这个函数

转载 作者:行者123 更新时间:2023-11-30 17:01:58 25 4
gpt4 key购买 nike

我正在用 angularjs 开发一个小应用程序:-

我正在努力删除联系人。一切正常,但 this.openModal() 抛出一个未定义的错误,即使它是在同一个 JS 中定义的。

对如何一起使用 this 和 $scope 有一些困惑。谁能帮忙?

$scope.deleteContact = function ()
{
var delNo = $scope.contactNumber;
var delName = $scope.contactName;

var person = {};
person['phone'] = delNo;

...
...
$timeout(function(){
delete $scope.contacts[person['phone']];
});

$scope.activeChats={};
$scope.showContactName = false;
this.openModal();

console.log("Delete success");

}

编辑:

this.openModal 是我定义如下的函数

this.openModal = function (input) {
this.modalOpen = !this.modalOpen;
// RESET
this.showNewMessage = false;
this.showEditGroup = false;
this.showAddContact = false;
this.showPersonSettings = false;
this.showUserProfile = false;

if (input == "newmessage"){
this.showNewMessage = true;
} else if (input == "showEditGroup"){
this.showEditGroup = true;
} else if (input == "newcontact"){
this.showAddContact = true;
} else if (input == "userprofile"){
this.showUserProfile = true;
} else if (input == "usersettings"){
this.showPersonSettings = true;
}
}

最佳答案

目前还不完全清楚您在做什么,但我想您在执行异步函数时遇到了一些上下文问题。尝试将 $scope 分配给一个局部变量,在您的函数 block 中关闭它并在 asnyc 函数 block 中使用该变量。

$scope.deleteContact = function ()
{
var person = {
phone: $scope.contactNumber
};

...

// save scope reference to local variable
var scope = $scope;

$timeout(function(){
// use saved scope
delete scope.contacts[person['phone']];
});

$scope.activeChats={};
$scope.showContactName = false;
this.openModal();

console.log("Delete success");
}

还有另一种方法可以在 Angular 的代码中做一些类似的事情。那就是 angular.bind。在您的 $timeout 中使用它。相似之处在于您在执行时提供函数的上下文,因此 this 就是您提供的内容。在以下情况下,我提供 $scope 作为异步函数的执行上下文,this 使用 this 引用它:

$timeout(angular.bind($scope, function(){
// context (this) is actually $scope
delete this.contacts[person['phone']];
}));

关于javascript - Angularjs $scope 和这个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28668883/

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