关于 javascript:如何观察或观察 AngularJS 服务中的输入属性变化?

How to observe or watch an input attribute change in an AngularJS Service?

我的 UI 中有一个单选按钮,它有一个 ngModel,它通过 ngDisabled 启用/禁用另一个输入。

我想在输入元素启用/禁用并且必须在 Angular 服务中完成时观察/观察/触发。我根本找不到如何做到这一点。以下是我在指令中的做法:

1
2
3
4
5
6
7
8
9
10
11
12
// for the case of field that might be ng-disabled, we should skip validation
// Observe the angular disabled attribute
attrs.$observe("disabled", function(disabled) {
  if (disabled) {
    // Turn off validation when element is disabled
    cancelValidation();
  } else {
    // Re-Validate the input when enabled
    var value = ctrl.$viewValue || '';
    ctrl.$setValidity('validation', validate(value, true));
  }
});

但是如何在服务中做到这一点???
我不希望有另一个指令,我真的希望通过服务来完成。

在问这个问题之前,我发现这个Is it possible to \\'watch\\' attributes\\' changes,我试过了

1
scope.$watch(function() {return element.attr('disabled'); }, function(newValue){});

但这似乎不起作用,至少当我启用/禁用我的单选按钮时(输入元素作为 ngDisabled 绑定到带有 ngModel 的单选按钮)

我还发现我们可以使用 jQuery.watch() 但我想坚持使用 vanilla javascript 或 jqLit??e。有可能吗?

编辑
我应该提到这个服务是独立的,无法访问控制器,因为它是一个表单验证工具,它不知道外部(至少不超过元素本身和他的范围)。如果需要,您可以查看并使用它:Angular-Validation 并且它支持指令和服务,具体取决于您希望验证发生的内容或位置,我的问题仅与服务中的代码有关。 pankajparkar 的答案帮助我解决了它...谢谢:)


我相信你的属性 disabled 带有类似 disabled="{{disable}}" 的插值,为什么你能够将 $observe 放在那个值上尝试将相同的东西更改为 $watch 将无法在那个 attribute 上工作,您还需要 $interpolate 服务来评估您的属性插值。这样实际值将得到评估是 disabled 还是 '' 并且如果更改它的状态,则 $watch 函数将被相应地触发。

代码

1
2
3
4
5
scope.$watch(function() {
   return $interpolate(element.attr('disabled'))(scope); //this will evaluate attribute value `{{}}``
}, function(newValue){
    //your code would be here
});


Scope 的目的是将应用程序的表示和业务逻辑"粘合在一起"。将 $scope 传递给服务没有多大意义。
您始终可以在使用此服务(与单选按钮视图关联的服务)初始化控制器时执行 $scope.$watch 并触发对服务的调用以进行所需的更新。

如果你已经可以在你的服务中访问这个变量(从控制器获取它)你应该能够做到:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
app.service('myservice',function(){
    this.listen = function($scope) {
        $scope.$watch(function(){return someScopeValue},function(){
           //$scope.dosomestuff();
        });
    }
});

//your controller

function myCtrl($scope,myservice) {
    $scope.listen = function() {
        myservice.listen($scope);
    }

    //call your method
    $scope.listen();
}