【问题标题】:AngularJS: late-binding of ng-model to dom elementAngularJS:ng-model 到 dom 元素的后期绑定
【发布时间】:2014-05-20 23:15:47
【问题描述】:

我有一个网页,其中包含一些我无法编​​辑的 HTML 元素。我想动态地将 ng-model 属性附加到这些属性上,并让 AngularJS 将它们重新绑定到范围。可以找到我想要完成的简化示例here

<script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<script>
function MyCtrl($scope) {
    $scope.myModel1 = "Hi";
    $scope.myModel2 = "there";
    var myModel2 = angular.element("#myModel2");
    //This won't work
    myModel2.attr("ng-model", "myModel2");
}
</script>
<div ng-app ng-controller="MyCtrl">
    <input type="text" ng-model="myModel1"/>
    <!-- I can't touch this -->
    <input type="text" id="myModel2" />
</div>

【问题讨论】:

    标签: javascript angularjs binding


    【解决方案1】:

    你需要使用$compile (docs)

    $compile(myModel2.attr("ng-model", "myModel2"))($scope);
    

    demo

    当您加载页面时,Angular 会自动在 HTML 上使用 $compile,这就是它知道将哪些指令分配给哪些元素的方式。如果您只是像尝试的那样更改属性,那么角度不知道。你必须使用$compile

    【讨论】:

    • 对不起,我没有足够的声望点来接受你的回答;当我这样做时,我会回来的!
    • 谢谢莫绍。这是 sn-p 如何对 ng-model 进行后期绑定以选择: $compile(angular.element('#timezone'), angular.element(' #timezone').attr('ng-model', 'vm.timeZone'))($scope);
    猜你喜欢
    • 2019-06-16
    • 1970-01-01
    • 2013-05-12
    • 1970-01-01
    • 2018-08-30
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多