$ scope的双向绑定不适用于新添加的小部件

时间:2015-09-20 11:16:54

标签: angularjs

点击后,我试图在表单中添加一个输入框。新添加的文本已获得ng-model =" name"。仍然在文本框中填充名称varialble。我想动态地将小部件添加到ng控制部分,并且应该能够使用$ scope变量进行双向绑定。有什么方法可以做到这一点。?

<div ng-app = "myapp">
<div ng-controller = "HelloController" >
    <a ng-click="clickMe()">Click</a>
    <form name="studentForm" id="myform">
    <input name="name" ng-model="name" type="text">
    <div ng-bind="name">
    </div>
    </form>
</div>

<script>
    var aa = angular.module("myapp", []);
    aa.controller("HelloController", function($scope) {
        $scope.name = "Raman";
        $scope.clickMe = function(){
            $('#myform').append('<input name="name2" ng-model="name" type="text">');
        }
    });
</script>

1 个答案:

答案 0 :(得分:1)

bad praxis angular / jquery mixup

AngularJS在页面加载时分析您的标记。之后注入的任何代码都不会被angularJS考虑。要向angularJS添加新标记,您需要调用角度$compile服务。

var aa = angular.module("myapp", []);
aa.controller("HelloController", function($scope,$compile) {
    $scope.name = "Raman";
    $scope.clickMe = function(){
        var insert = $compile('<input name="name2" ng-model="name" type="text">')($scope);
        $('#myform').append(insert);
    }
});

更好的角度方式

但是作为一般提示:如你的代码所示,混合angularJS和jQuery并不是很好的实践。您可以简单地将输入字段添加到html标记中,并使用angularJS有条件地显示它。

<div ng-app="myapp">
    <div ng-controller="HelloController">
        <a ng-click="clickMe()">Click</a>
        <form name="studentForm" id="myform">
            <input name="name" ng-model="name" type="text">
            <div ng-bind="name"></div>
            <input name="name2" ng-model="name" type="text" ng-show="showNameField">
        </form>
    </div>
</div>
<script>
    var aa = angular.module("myapp", []);
    aa.controller("HelloController", function($scope) {
        $scope.name = "Raman";
        $scope.showNameField = false;
        $scope.clickMe = function(){
            $scope.showNameField = true;
        }
    });
</script>

快速而肮脏的角度方式

或者您甚至可以直接在ng-click指令中修改变量。更进一步的js将表达式中的空变量解释为false值,这就是为什么你甚至不需要在控制器函数中初始化变量:

<div ng-app="myapp">
    <div ng-controller="HelloController">
        <a ng-click="showNameField = true">Click</a>
        <form name="studentForm" id="myform">
            <input name="name" ng-model="name" type="text">
            <div ng-bind="name"></div>
            <input name="name2" ng-model="name" type="text" ng-show="showNameField">
        </form>
    </div>
</div>
<script>
    var aa = angular.module("myapp", []);
    aa.controller("HelloController", function($scope) {
        $scope.name = "Raman";
    });
</script>