5

我正在 AngularJS 中实现一个简单的微调器控件,我想对用户输入和 +/- 按钮的更改做出反应。这是我的HTML

<input type='button' ng-click="MyProperty = MyProperty - 1" value="-">
<input type='text' ng-model="MyProperty" ng-change="log('changed from ngChange')">
<input type='button' ng-click="MyProperty = MyProperty + 1" value="+">

但这将仅跟踪“用户更改”,因为根据文档ngChange仅支持用户交互更新

所以现在我正在$scope.$watch按照 Frederik的建议进行研究:

$scope.$watch('MyProperty', function() {
  $scope.log('changed from $watch');
});

plunker 演示

但这似乎不太对劲。

  1. 首先,它不是声明性的,您必须搜索代码MyTestProperty才能找到此绑定。
  2. 如果您想放置$scope.log在单独的模型中,则必须注入$scope或在控制器中进行绑定。据我了解,这两种方式都不被认为是最佳实践。

由于许多其他原因,有些人认为这$watch通常是一件坏事。但是那里建议的解决方案(log直接调用 ngClick)对我来说并没有太大的不同。基本上你必须手动跟踪所有的变化,如果有新的演员出现,你必须在那里复制你的逻辑。

所以问题是:有没有一种方法可以让你在没有 $watch 的情况下自动跟踪模型更新?如果现在有这种方法,那么为此实施您自己的指令的想法有多糟糕?

4

3 回答 3

4

有几种方法可以做到这一点,但最优雅的方法是要求输入的 ngModel,然后使用它来查看/操作值。

这是更新 的Plunker

.directive('outputIt', function() {
    return {
      restrict: 'A',
      scope: {
        outputIt: '&'
      },
      require: '?ngModel',
      link: function(scope, element, attrs, ngModelCtrl) {
        ngModelCtrl.$parsers.push(function(val) {
          //console.log("the model was changed by input")
          scope.outputIt()(val);
        });
        ngModelCtrl.$formatters.push(function(viewValue) {
          //console.log("the model was changed from outside.");
          scope.outputIt()(viewValue);
          return viewValue;
        });
      }
    }
  })


要了解有关它的更多信息,这里有一篇关于它的非常酷的文章: Atricle

祝你好运!

于 2014-08-18T13:04:39.887 回答
3

你有没有研究过 ES5 的方式?它本质上是 javascript 的原生 $watch 功能。不同之处在于您将 set/get 函数与属性一起封装,而 $watch 可以在外部任何地方应用。

var MyCtrl = function(){
  this._selectedItem = null;
};

Object.defineProperty(MyCtrl.prototype, "selectedItem", {
    get: function () {
        return this._selectedItem;
    },
    set: function (newValue) {
        this._selectedItem = newValue;

        //Call method on update
        this.onSelectedItemChange(this._selectedItem);
    },
    enumerable: true,
    configurable: true
});
于 2014-08-18T12:57:57.543 回答
-1

当然使用:

<input type="number" />

这将创建您的微调器 =)

于 2014-08-18T13:07:49.780 回答