AngularJS-$编译一个元素并将作用域传递给它

AngularJS - $compile-ing an element and passing the scope to it

本文关键字:作用域 元素 一个 编译 AngularJS-      更新时间:2023-09-26

我有一个简单的指令:

<div my-directive>
    <span ng-click="reveal()">Click Me</span>
    <!-- And other stuff -->
</div>

当我按下Click Me时,会打开一个模态,其中包含一个用于编辑某些内容的表单。所有这些内容都属于CCD_ 2数据的一部分。现在,假设这个对象只有一个名为name的条目。

这就是我为我的指令所做的:

scope.reveal = function()
{
   var el = $compile('<input type="text" ng-model="scope.form.name" />')(scope);
   // Now launch the modal
}

因此,模态确实打开了,并且正确地显示了scope.form.name的内容。但是,如果我关闭模态并再次打开它,则不会保存该值(即,scope.form.name不会在指令中更新)。

我能做的最好的事情是什么?

使用angularjs,通常不会编译元素并将其添加到DOM中。您应该在模板中声明您的表单,并将ng-show绑定到作用域上的属性以显示/隐藏您的表单。

<div my-directive>
    <span ng-click="form.show = true">Click Me</span>
    <form ng-show="form.show">
        <input type="text" ng-model="form.name" />
    <form>
</div>