如何使用 jQuery 为指令模板中的元素设置值
How to set value to element in directive template with jQuery
我有一些指令和一些模板。
angular.module('testModule', [])
.directive('testInput', function () {
var id = 1;
return {
restrict: 'E',
replace: true,
scope: {
model: '='
},
template: '<div><input type="text" id="{{uniqueId}}"/></div>',
link: function (scope) {
scope.uniqueId = "test" + id++;
$('#' + scope.uniqueId).val(33);
}
}
});
我想为具有 uniqueId 的元素设置值,但我做不到。
你能帮助我吗?
Plunker 上有示例:example。
谢谢。
编辑。
我找到了另一个解决方案。
.......
template: '<div><input type="text" id="{{uniqueId}}" ng-value="someModel"/></div>',
link: function (scope, elem, attrs) {
scope.uniqueId = "test" + id++;
scope.someModel = 887;
}
.......
示例:Plunker
不幸的是,JQuery 超出了 angular 的 $digest
周期。更简单的方法是使用 link
函数通常提供的功能,它可以访问三个变量 scope
、elem
和 attrs
,因此您可以着手做这样的事情:
link: function (scope, elem, attrs) {
scope.uniqueId = "test" + id++;
elem.children().first()[0].value = 33;
}
这是你的 plunk 的一个分支
我有一些指令和一些模板。
angular.module('testModule', [])
.directive('testInput', function () {
var id = 1;
return {
restrict: 'E',
replace: true,
scope: {
model: '='
},
template: '<div><input type="text" id="{{uniqueId}}"/></div>',
link: function (scope) {
scope.uniqueId = "test" + id++;
$('#' + scope.uniqueId).val(33);
}
}
});
我想为具有 uniqueId 的元素设置值,但我做不到。 你能帮助我吗? Plunker 上有示例:example。 谢谢。
编辑。
我找到了另一个解决方案。
.......
template: '<div><input type="text" id="{{uniqueId}}" ng-value="someModel"/></div>',
link: function (scope, elem, attrs) {
scope.uniqueId = "test" + id++;
scope.someModel = 887;
}
.......
示例:Plunker
JQuery 超出了 angular 的 $digest
周期。更简单的方法是使用 link
函数通常提供的功能,它可以访问三个变量 scope
、elem
和 attrs
,因此您可以着手做这样的事情:
link: function (scope, elem, attrs) {
scope.uniqueId = "test" + id++;
elem.children().first()[0].value = 33;
}
这是你的 plunk 的一个分支