【问题标题】:angular watch - update variable outside function scope角度手表 - 更新函数范围外的变量
【发布时间】:2014-08-11 03:42:07
【问题描述】:

从 angularjs 开始,这个问题让我很困惑。

如何以及如何确保当 watch 函数第二次运行时(在初始化时)testValue 被“更改”。

<div ng-controller="MyCtrl"></div>

和js:

var myApp = angular.module('myApp',[]); 
function MyCtrl ($scope) {
  var testValue = null;
  $scope.watchMe = null;        
  $scope.$watch('watchMe', function () {
    console.log('testValue is', testValue);        
    if(testValue !== null){`enter code here`
        console.log('i want to do something different the 2nd time this code runs - but i never get in here...');
    }
    testValue ="changed";
  });
};

然后是小提琴:jsfiddle example of the code

非常感谢

【问题讨论】:

  • 角度太难了

标签: javascript angularjs


【解决方案1】:

您尝试使用手表的方式不是很正确

watch 用于对模型更改做出反应以触发一些进一步的操作

所以你需要设置一个模型作为监视表达式并监听它,以便在有任何变化时调用监视

<div ng-app="myApp" ng-controller="MyCtrl">
  <input type="text" ng-model="name" placeholder="Enter your name">
  <p>{{greeting}}</p>
</div>

和js:

var myApp = angular.module('myApp',[]); 
function MyCtrl($scope) {
  $scope.name = "";

  $scope.$watch("name", function(newValue, oldValue) {
    if ($scope.name.length > 0) {
      $scope.greeting = "Greetings " + $scope.name;
         console.log("change detected: " + newValue);
    }
  });
}

【讨论】:

  • 非常感谢您抽出宝贵的时间来回答 - 虽然问题出在其他地方 - 请参阅答案
【解决方案2】:

原来问题不在于手表,而在于控制器被调用了两次。我不确定它为什么在 the fiddle 中这样做,但我添加了一个日志以明确这是问题所在。

所以要清除 - testValue 一直为空,因为在 watch 函数运行后,控制器函数再次运行并覆盖 var testValue。

这可能是由于很多原因 - 在我的例子中,我将控制器分配给一个元素,如小提琴中所示。

<div ng-controller="MyCtrl"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 2015-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多