【问题标题】:$watch to check varible defined in the scope AngularJS$watch 检查在 AngularJS 范围内定义的变量
【发布时间】:2016-04-21 06:31:46
【问题描述】:

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

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

指令代码

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

html代码

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

【问题讨论】:

  • 你有错误的手表代码,它应该是你的指令中的scope.$watch('show'
  • 非常感谢@PankajParkar 我在这个错误上花了很多时间。你是对的,这是错误
  • 我觉得这样比较适合以后参考

标签: javascript angularjs angularjs-directive angularjs-watch


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    相关资源
    最近更新 更多