【问题标题】:Angular Material $mdDialog - Can't access 'this' items in confirm functionAngular Material $mdDialog - 无法在确认功能中访问“this”项目
【发布时间】:2018-05-22 22:30:43
【问题描述】:

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

$mdDialog 指令是否存在与 controllerAs 语法有关的问题?

-

控制器:

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.notifications 或任何 this.variable,在角度 1 中,所有内容都应放在 $scope 变量下,即使用 $scope.notifications = {} 设置值并通过 var x = 获取值$scope.notifications
  • 呃,即使我知道情况并非如此。互联网上确实有人说这是一种糟糕的方法,并且文档建议将 controllerAs 语法与“this”项目一起使用
  • 是的 Angular 1 设计很差,但你应该接受他们的官方建议,如果你有好的做法,那么直接跳到 Angular 5 或者他们最近所说的,或者如果你仍然关注这个链接想使用 angular 1 使用工厂 stackoverflow.com/questions/29700783/…
  • ControllerAs 和 'this' 语法自角度 1 以来已在文档中提出

标签: javascript angularjs dialog angular-material


【解决方案1】:

this 在:

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

指的是$mdDialog.show()返回的promise的promise resolve函数,如果你想访问控制器的notifications成员你必须创建一个引用控制器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() {
    ...
  })
}

【讨论】:

  • 谢谢。完美运行
猜你喜欢
  • 2016-07-16
  • 1970-01-01
  • 2020-12-24
  • 1970-01-01
  • 2017-06-18
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多