【问题标题】:$watch not trigger without $scope.digest没有 $scope.digest 就不会触发 $watch
【发布时间】:2016-08-01 14:58:53
【问题描述】:

我正在编写自己的字典指令:

<div ng-controller="formController"> <dictionary label="Editable" model="bso.dictionnaryObject" required=true dictionary-object="dico"> </dictionary> </div>

“dico”值是通过控制器中的 GET 调用设置的,因此这意味着它没有像指令初始化时那样初始化

所以我留意了我的指令

 angular.module('dictionary', []).directive('myCustomer', function() {
return {
 templateUrl:  "dictionary.html",
    restrict: = "E",
    require: "^form",
    scope : {
        model: "=",
        dictionaryObject: "=",
        label: "@",
        editable: "@",
    },
    link : function() {
      $scope.$watch("dictionaryObject", function(newVal, oldVal){
                console.log(oldVal);
                console.log(newVal);
            }, true);
}};});

从 rootScope :

app.controller('formController', function ($scope) {

 $.get("http://framework:8787/Services/dictionary",
        function (data) {
            $scope.dico = data;
            $scope.$digest();
        });}

所以添加 $scope.$digest 是我发现触发手表的唯一方法。 有什么办法不调用 $scope.digest() 并触发我的手表?

谢谢

【问题讨论】:

  • 你应该手动 $apply 你的 $scope 更改,而你不使用像 $http 这样的角度服务,已经可以做到这一点。
  • 如果您使用 jquery 或任何其他 javascript,您需要手动消化 \ 应用更改,因为 angular 会丢失 angular 循环之外的代码轨迹。

标签: javascript angularjs watch


【解决方案1】:

这不起作用,因为$.get() 不知道应该执行摘要循环。 您应该为此使用角度方式:

$http.get("http://framework:8787/Services/ofo/rest/dictionary/OrganisationStatusAvailabilityCode",
        function (data) {
            $scope.dico = data;
            //$scope.$digest(); If you use $http, the digest it's implicit
        });}

【讨论】:

  • 非常感谢您教给我这一点以及非常快速的答案!
猜你喜欢
  • 1970-01-01
  • 2016-07-17
  • 2018-03-21
  • 1970-01-01
  • 2014-12-31
  • 1970-01-01
  • 2021-05-17
  • 1970-01-01
  • 2019-11-19
相关资源
最近更新 更多