使用Angular Directive用$scope属性更新DOM-只要指令运行(无需等待事件)

Update DOM with $scope property using an Angular Directive - as soon as the directive runs (without waiting for an event)

本文关键字:运行 指令 事件 等待 Directive Angular scope DOM- 更新 属性 使用      更新时间:2024-02-06

如果你看看这个小提琴:http://jsfiddle.net/rodhartzell/u4zVd/1/

您可以看到,在处理其中一个订阅的事件之前,该指令不会考虑模型$scope.bar。你知道有什么方法可以让指令在绑定后立即识别模型吗?

            element.keyup(scope.onEdit)
            .keydown(scope.onEdit)
            .focus(scope.onEdit)
            .live('input paste', scope.onEdit);
        element.on('ngChange', scope.onEdit);

我会以不同的方式处理整个问题。与其绑定事件,我会设置一个长度如下的手表:

现场演示(点击)。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.bar = 'something';
});
app.directive('myMaxlength', function($compile) {
  return {
    restrict: 'A',
    scope: { bar: "=ngModel" },
    link: function(scope, element, attrs) {
      var counterElem = angular.element('<span>Characters remaining: {{charsRemaining}}</span>');
      $compile(counterElem)(scope);
      element.parent().append(counterElem);
      scope.$watch(
        function() {
          return scope.bar.length; 
        },
        function(newLength) {
          scope.charsRemaining = attrs.myMaxlength - newLength;
        }
      );
    }
  };
});