gpt4 book ai didi

javascript - 使用 Angular 指令使用 $scope 属性更新 DOM - 一旦指令运行(无需等待事件)

转载 作者:行者123 更新时间:2023-11-29 10:16:28 25 4
gpt4 key购买 nike

如果你看看这个 fiddle :http://jsfiddle.net/rodhartzell/u4zVd/1/

您可以看到模型 $scope.bar 没有被指令考虑,直到处理了一个订阅的事件。您是否知道一种方法可以使指令在绑定(bind)后立即识别模型?

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

最佳答案

我会以不同的方式处理整个问题。而不是绑定(bind)事件,我会像这样设置一个长度 watch :

Live demo here (click).

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;
}
);
}
};
});

关于javascript - 使用 Angular 指令使用 $scope 属性更新 DOM - 一旦指令运行(无需等待事件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20356659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com