根据实际情况,这有点复杂。我的解决方案假设元素在 dom 就绪时可用,而不是使用部分加载。演示
JS
function setAngularValue($elem, value) {
var scope = $elem.scope();
var ngModelName = $elem.attr('ng-model');
if(ngModelName) {
var $injector = $elem.injector();
//get the parse service to use on the ng-model
var $parse = $injector.get('$parse');
var ngModel = $parse(ngModelName);
scope.$apply(function() {
//this will allow any ng-model value ex: my.object.value
ngModel.assign(scope, value);
});
}
else {
//fallback if there is no model, weird case imho
$elem.val(value);
}
}
$(document).ready(function() {
var $elem = angular.element('#myJqueryId');
var value = 'some value';
setAngularValue($elem, value);
});
HTML
<p>Hello {{my.angular.model}}!</p>
<input id="myJqueryId" ng-model="my.angular.model"></input>
链接
- $注射器
- $解析