AngularJS 如果模型和绑定由 jQuery 设置,则模型绑定不起作用

AngularJS model-bind not working if the model and bind are set by jQuery

我正在学习 Angular JS,但我停留在一个非常基本的步骤上。

这是我的测试代码:

<!DOCTYPE html>

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

        <script>
            function enable()
            {
                $("#test_model").attr("data-ng-model", "test");
                $("#test_bind").attr("data-ng-bind", "test");
            };
        </script>
    </head>

    <body>
        <div data-ng-app="">
            <div>
                <input type=text id=test_model />
            </div>

            <div>
                <p id=test_bind></p>
            </div>

            <button onclick=enable()>Enable</button>
        </div>
    </body>
</html>

在这里,我期望发生的是,当单击 Enable 按钮时,它应该启用绑定,因此如果在 #test_model 中输入任何内容输入,它应该更新 #test_bind 段。但它不起作用。

我可以看到 Firebug 单击 Enable 按钮时属性(data-ng-modeldata-ng-bind)正在更新,但它不会像静态编码(对模型和绑定参数进行硬编码)那样生效。

如果我对其进行静态编码,然后我注意到 3 个新的 classes(ng-pristineng-untouchedng-valid)会自动添加到 #test_model 并将一个新的 class (ng-binding) 添加到 #test_bind。所以我将 enable() 函数更改为:

function enable()
{
    $("#test_model").attr("data-ng-model", "test");
    $("#test_bind").attr("data-ng-bind", "test");

    $("#test_model").addClass("ng-pristine");
    $("#test_model").addClass("ng-untouched");
    $("#test_model").addClass("ng-valid");

    $("#test_bind").addClass("ng-binding");
};

但还是不行。

我错过了什么?

如果您想动态添加 Angular 指令,例如 ng-model、ng-bind 等。 您必须创建自己的指令并使用 $compile.

您可以使用 angular ng-show 或 ng-switch 切换显示 DOM 没有绑定的元素和具有 ng-model 和您需要的其他属性的元素。