$watch检查在作用域 AngularJS 中定义的变量

$watch to check varible defined in the scope AngularJS

本文关键字:定义 变量 AngularJS 作用域 watch 检查      更新时间:2023-09-26

我有以下指令来显示警报,所以我想在显示变量更改为星号运行时捕获超时,我该怎么做?

link 函数仅在第一次调用,但所有变量 show 、消息和类型都未定义

指令代码

 angular.module('pysFormWebApp')      
    .directive('alertDirective', 
    function  alertDirective ($timeout) {   
    return {
        restrict : 'E',
        scope : {
            message : "=",
            type : "=",
            show : "=",
            test : "="
        },
        controller : function ($scope) {
            $scope.closeAlert = function () {
                $scope.show = false;
                $scope.type = "alert alert-dismissable alert-";
                $scope.message = "";
            };
            $scope.getStrongMessage = function (type) {
                var strongMessage = "";
                if(type == "success"){
                    strongMessage = "'xC9xito ! ";
                } else if(type == "warning"){
                    strongMessage = "Cuidado ! ";
                return strongMessage;
            }
        },
        link: function(scope, element, attrs) {
            scope.$watch(scope.show, 
             function (newValue) {
             console.log(newValue); 
             },true);
        },
        templateUrl : "views/utilities/alert.html"
    };
});

HTML 指令代码

<div ng-show="show">
    <div class="alert alert-dismissable alert-{{type}}">
        <button type="button" class="close" ng-click="closeAlert()">&times;</button>
        <strong>{{getStrongMessage(type)}}</strong> {{  message | translate }} 
    </div>
</div>

控制器示例

  $scope.info.alert = {
    message: "EXPOTED-SUCCESS",
    type: "success",
    show : true
  };

网页代码

<alert-directive  message="info.alert.message" 
          type="info.alert.type" 
          show="info.alert.show">
</alert-directive>

在范围变量上设置监视时出错。基本上$watch将第一个参数作为string/function在每个摘要周期上进行评估,第二个参数将是回调函数

//replaced `scope.show` by `'show'` 
scope.$watch('show', function (newValue) {
   console.log(newValue); 
},true);