javascript - $watch 检查 AngularJS 范围内定义的变量

标签 javascript angularjs angularjs-directive angularjs-watch

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

链接函数仅在第一次被调用,但所有变量显示、消息和类型均未定义

指令代码

 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>

Controller 示例

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

html代码

<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);

关于javascript - $watch 检查 AngularJS 范围内定义的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34814882/

相关文章:

javascript - 通过Ajax运行php脚本

javascript - 有没有办法在 Angular 2 Typescript 组件中对相同类型的变量进行分组?

javascript - AngularJS 指令读取当前 templateURL

javascript - angular.copy() 在 setTimeout() 中不起作用

css - 列表的 Angular 指令和 ng-repeat;不继承父类

angularjs - 在运行时动态注册指令

javascript - 图像轮播 onmouseover data-slide-to

javascript - meteor 登录电子邮件域预定义

javascript - 如何获取 Angular 表单中的元素并将它们附加到列表中?

javascript - 更改元素的 CSS 5 秒,但如果下一个事件仍在 5 秒内则坚持