programing

Angular material $mdToast 메시지 유형에 따라 Toast 색상을 변경하는 방법은 무엇입니까?

minxs 2023. 3. 7. 22:02
반응형

Angular material $mdToast 메시지 유형에 따라 Toast 색상을 변경하는 방법은 무엇입니까?

$mdToast.simple().content("some test"), 성공 등의 등으로 하는 방법이 .에러, 경고, 성공 등의 에러 메시지의 종류에 따라, 그 색상을 빨강, 노랑 등으로 변경하는 방법이 다릅니다.

이것과 비슷한 질문입니다.

테마를 지정하면 보다 쉬운 방법이 있습니다.

$mdToast.simple().content("some test").theme("success-toast")

그리고 CSS에서는:

md-toast.md-success-toast-theme {
    background-color: green;
    ...
}

메시지 유형을 통합하여 테마를 동적으로 선택할 수 있습니다.

업데이트: Charlie Ng가 지적한 바와 같이 등록되지 않은 커스텀 테마의 사용에 관한 경고를 피하기 위해 테마 공급자를 사용하여 모듈에 등록합니다.$mdThemingProvider.theme("success-toast")

다른 업데이트:2015년 12월 2일(v1.0.0+)에 획기적인 변화가 발생했습니다.이제 다음을 지정해야 합니다.

md-toast.md-success-toast-theme {
    .md-toast-content {
        background-color: green;
        ...
    }
}

★★★★★★
올바른 구현을 위해서는 아래의 rlay3ssolution을 사용하십시오:!

★★★★
하는 데 에,jhblacklocks의를 사용하여 이렇게 하기로 .

var displayToast = function(type, msg) {

    $mdToast.show({
        template: '<md-toast class="md-toast ' + type +'">' + msg + '</md-toast>',
        hideDelay: 6000,
        position: 'bottom right'
    });
};

또한 .css 파일에 다른 유형을 추가했습니다.

.md-toast.error {
    background-color: red;
}

.md-toast.success {
    background-color: green;
}

이것이 가장 아름다운 방법인지는 모르겠지만, 각 대화 상자 유형에 대한 템플릿 파일은 필요하지 않으며 사용자 정의 텍스트를 표시하는 것은 매우 쉽습니다.

테마 등록:

$mdThemingProvider.theme("success-toast");
$mdThemingProvider.theme("error-toast");

css 추가:

md-toast.md-error-toast-theme div.md-toast-content{
    color: white !important;
    background-color: red !important;
}

md-toast.md-success-toast-theme div.md-toast-content{
    color: white !important;
    background-color: green !important;
}

용도:

$mdToast.show(
    $mdToast.simple()
        .content(message)
        .hideDelay(2000)
        .position('bottom right')
        .theme(type + "-toast")
);

이 링크에서는 요소의 배경색을 변경할 수 없으며 항상 고정되어 있음을 알 수 있습니다.

https://github.com/angular/material/blob/master/src/components/toast/toast-theme.scss

이는 토스트에 대한 재료 설계 가이드라인에 배경이 항상 동일하게 유지된다고 명시되어 있기 때문입니다.

https://www.google.com/design/spec/components/snackbars-toasts.html#snackbars-toasts-specs

해 주세요.background[ Specespecifications list 。

의 색에 언급이 , 의 색에 언급이 없다는 하고 있습니다그것은, 다음에 오는 것을 암시하고 있습니다.backgroundPaletteGitHub Link CSS는 '50'입니다.

「 」를 warn즉 토스트accent부터 -ted one, "ted"를 합니다.action toast)를 md-warn ★★★★★★★★★★★★★★★★★」md-accent를 참조해 주세요.

$mdToast.show({
    template: '<md-toast>\
        {{ toast.content }}\
        <md-button ng-click="toast.resolve()" class="md-warn">\
            Ok\
        </md-button>\
    </md-toast>',
    controller: [function () {
        this.content = 'Toast Content';
    }],
    controllerAs: 'toast'
});

입니다.default폼은 성공을 암시한 액션 보고서를 의미합니다.만약 더 많은 관심이 필요하다면 동작 버튼을 설정함으로써 강제로 닫다 '재시도', '문제 보고', '상세 정보' 등의 작업을 추가합니다. 이 작업을 사용하여 클릭을 확인하고 기술 정보를 기록할 수 있습니다.예는 당신이 필요로 하는 것과 다르다.

ray3의 답변에 한 걸음 더.

0.7.1의 Angular Material은 등록되지 않은 테마에 경고를 추가했습니다.https://github.com/angular/material/blob/master/CHANGELOG.md#071--2015-01-30

테마가 등록되지 않은 경우 토스트가 표시될 때마다 다음과 같은 경고 메시지가 콘솔에 표시됩니다.

attempted to use unregistered theme 'custom-toast'
angular.js:12416 Attempted to use unregistered theme 'custom-toast'. 
Register it with $mdThemingProvider.theme().

경고를 없애려면 각진 앱에서 '커스텀 토스트' 테마를 구성해야 합니다.

angular.module('myApp', ['ngMaterial'])
.config(function($mdThemingProvider) {
  $mdThemingProvider.theme('custom-toast')
});

다음과 같이 사용합니다.

$mdToast.simple().content("some test").theme("custom-toast");

참고 자료: https://material.angularjs.org/latest/ #/Theming/04_multiple_temes

간단한 토스트 콜에 대해 물어보셨잖아요.데모와 같은 맞춤형 토스트 를 시도해보고 템플릿에 클래스를 추가해도 될까요?

JS

$mdToast.show(
  controller: 'ToastCtrl',
  templateUrl: 'views/shared/toast.html',
  hideDelay: 6000,
  position: $scope.getToastPosition()
)

템플릿

<md-toast class="flash">
  <span flex>Custom toast!</span>
  <md-button ng-click="closeToast()">
   Close
  </md-button>
</md-toast>

CSS

md-toast.flash {
  background-color: red;
  color: white;
}

컨트롤러(커피)

'use strict'

###*
 # @ngdoc function
 # @name angularApp.controller:ToastCtrl
 # @description
 # # ToastCtrl
 # Controller of the angularApp
###
angular.module('angularApp')
  .controller 'ToastCtrl', ($scope) ->
    $scope.closeToast = ()->
      $mdToast.hide()

다른 선택권을 주자면$mdToast이런 식으로 쉽게 인스턴스화할 수 있는 토스트 프리셋을 정의할 수 있습니다. 텍스트 내용을 변경하는 방법을 이해하는데 어려움을 겪고 있는데, 어떻게 생각하십니까?

$mdToast.show(
  $mdToast.error()
);

사전 설정은 https://material.angularjs.org/latest/api/service/$mdToast에서 설명한 바와 같이 정의되어 있습니다.

$mdToastProvider.addPreset('error', {
  options: function() {
    return {
      template:
        '<md-toast>' +
          '<div class="md-toast-content">' +
          '</div>' +
        '</md-toast>',
      position: 'top left',
      hideDelay: 2000,
      toastClass: 'toast-error',
      controllerAs: 'toast',
      bindToController: true
    };
  }
});

처음에는 솔루션을 선호했지만, 주제 공급자에 건배를 위한 테마를 설정하는 것은 좋아하지 않습니다.이 솔루션은 어떻습니까?

JS(커피)

   if error
      message = ''

      if error.reason is 'Incorrect password'
        message = 'Email and password combination is incorrect'
      if error.reason is 'User not found'
        message = 'No account found with this email address'

      $mdToast.show(
        templateUrl:  'client/modules/toasts/toastError.html'
        hideDelay:    3000
        controller: ( $scope ) ->
          $scope.message    =  message
          $scope.class      = 'error'
          $scope.buttonLabel = 'close'
          $scope.closeToast = ->
            $mdToast.hide()
      ).then( ( result ) ->
        if result is 'ok'
          console.log('do action')
      )

그 후 HTML(JADE)

md-toast(ng-class="class")
  span(flex) {{message}}
  md-button.md-action(ng-click="closeToast()") {{buttonLabel}}

저는 이 기능을locals변수를 컨트롤러에 전달하지만 어떤 이유로 변수가 삽입되지 않습니다.(https://material.angularjs.org/latest/ #/api/material.components.toast/service/$mdToast 체크리스트)show기능)

다음으로 CSS(STYLUS)를 종료합니다.

md-toast.success
  background-color    green

md-toast.error
  background-color    red

개요: 이 경우 컨트롤러에 프리필하는 커스텀플레이스 홀더를 지정할 수 있는 템플릿이 있습니다.이 솔루션은 나에게 효과가 있다.

공장이나 css와 함께 할 수 있습니다.

(function () {
  'use strict';

  angular
    .module('app.core')
    .factory('ToastService', ToastService);

  /** @ngInject */
  function ToastService($mdToast) {

    var service = {
      error: error,
      success: success,
      info : info
    };

    return service;

    //////////

    function success(text) {
      $mdToast.show(
        $mdToast.simple()
          .toastClass("toast-success")
          .textContent(text)
      );
    }

    function info(text) {
      $mdToast.show(
        $mdToast.simple()
          .toastClass("toast-info")
          .textContent(text)
      );
    }

    function error(text) {
      $mdToast.show(
        $mdToast.simple()
          .toastClass("toast-error")
          .textContent(text)
      );
    }
  }
}());

그리고 css.

.toast-error .md-toast-content{
  background-color: rgb(102,187,106) !important;
}

.toast-info .md-toast-content{
  background-color: rgb(41,182,246) !important;
}

.toast-error .md-toast-content{
  background-color: rgb(239,83,80) !important;
}

언급URL : https://stackoverflow.com/questions/28481029/how-can-i-change-the-color-of-toast-depends-on-message-type-in-angular-material

반응형