AngularJS - 指令DOM操作/更改动态元素不更新视图

时间:2017-12-13 16:55:28

标签: javascript angularjs model-view-controller angularjs-directive

JSFiddle:http://jsfiddle.net/ADukg/16844/

在我的应用程序中,我试图通过onClick指令操作元素,该指令似乎正在更改控制器的变量/对象,因为它正确地将新值记录到控制台,但这不会在视图本身中显示

例如,我有一个填充的通知数组,在指令中使用.length = 0清除,当我将数组记录到控制台时,它显示它是空的,但在视图中,项目重复在ng-repeat列表中,列表仍然填充了人口初始状态下数组中的项目。

我的指令中没有任何更改更新视图,但是当我在控制器函数中执行相同的操作时,视图会更新。

指令:

app.directive('clearNotifications', function($mdDialog, $mdToast, $timeout) {
  return {
    restrict: 'A',
    controller: 'notificationsController',
    controllerAs: 'notifications',
    scope: false,
    bindToController: true,
    link: function($scope, element, attrs) {
      element.bind('click', function() {
        var notifications = $scope.notifications;
        console.log('notifications.test: ' + notifications.test);
        /* Show confirmation prompt dialog */
        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(element)
        /* On confirm */
        $mdDialog.show(confirm).then(function() {
            $scope.status = 'All notifications deleted';
            console.log($scope.status);
            /* Show notifications list loader */
            $scope.showLoader = true;
            $timeout(function() {
              $scope.showLoader = false;
            }, 1000)
            /* Clear notifications array */
            notifications.notifications.length = 0;
            console.log($scope.notifications.notifications);
            $scope.noNotifications = true;
            /* Reset filters to 'All' default */
            notifications.filters = angular.copy(notifications.resetFilters);
            /* Show toast */
            //$scope.toastTitle = 'TEST';
            $mdToast.show(
              $mdToast.simple()
              .content('All notifications cleared')
              .action('Close')
              .position('bottom right')
              .hideDelay(500000)
            )
          },
          /* On cancel */
          function() {
            $scope.status = 'Notifications clearance cancelled';
            console.log($scope.status);
          })
      })
    }
  }
})

0 个答案:

没有答案