angularjs指令中的Ng-model

ng-model in angularjs directive

本文关键字:Ng-model 指令 angularjs      更新时间:2023-09-26

我试图创建一个指令,将创建不同类型和不同数字的输入(s)字段。这工作得很好,但我的问题是,我不能使用任何我的ng模型在我的指令的输入字段。我的代码如下:

HTML::

<form method="post" ng-submit="CheckAddReceivedGoods($event, limit)" novalidate>
     <ul class="checkboxUl" ng-repeat="cat in InvoicesProduct">
        <invoice-product info="cat" num="$index"></invoice-product>
    </ul>
</form>
AngularJS Code::

var apps = angular.module("ReceivedGoodsApps", ['ngRoute']);
    apps.directive("invoiceProduct", function () {
        return {
            restrict: "E",
            scope: {
                productList: "=info",
                pos: "=num"
            },
            template: '<div>',
            link: function (scope, element, attrs) {
                var template = '';
                position = scope.pos + 1;            
                HasUniqueSpecifier = scope.productList.HasUniqueSpecifier;
                if (HasUniqueSpecifier === "NoUniqueIdentifier") {
                    template += '<input type="text" ng-model="Quantity' +  position + '" />';                        
                } else if (HasUniqueSpecifier === "UniqueIdentifier") {
                  template += '<textarea rows="7" cols="35" ng-model="UniqueIdentifier' + position + '" ></textarea>';
                } else if (HasUniqueSpecifier === "SerialUniqueIdentifier") {
                     template += '<input type="text" ng-model="end' + position + '"  /> ';
                }
                element.find('div').append(template);
            }
        };
    });
    apps.controller("ReceivedGoodsCtrl", function ($scope, $http) {
        $scope.CheckAddReceivedGoods = function ($event, limit) {
            for (var i = 1; i <= limit; i++) {
                // $scope['Quantity' + i] is undefined
                // $scope['UniqueIdentifier' + i]  is undefined
                // $scope['start' + i] is undefined
            }
        };

这里有一些选项,都在评论中提到。

首先,如果您想搞乱DOM,您将希望使用编译函数而不是链接函数。也就是说,我认为你不必那样做。

在你的模板中,你可以这样做:

<input type="text" ng-model="quantity" ng-if="productlist.HasUniqueSpecifier === 'NoUniqueIdentifier'">

所以你根本不需要在DOM里瞎折腾——让angular来帮你处理。

同样重要的是:如果您正在构建一个隔离作用域指令,则不需要唯一定义您的模型名称。范围。第一个发票-产品实例上的数量与范围无关。数量在第二。他们是孤立的。所以你不需要通过编程来指定ng-model的名字。

在你的控制器($scope['Quantity'+i])中注释掉的东西说明了这一点。指令中的内容在父作用域中是无法访问的。这样做的一种方法是在指令上粘贴一种"返回值"属性,如果你在指令范围声明中添加quantity='=',你最终可以在那里粘贴一个父变量来接收用户的输入。或者您可以添加一个"on-finished"类型的方法属性,如

或者你可以完全跳过指令,只做一些ng-repeat。在这种情况下,您可以只使用$scope,而不是使用编程生成的模型名称。quantity =[],所以

有很多方法可以做到这一点,但一般来说,如果您直接操作DOM而不是使用ng-if和ng-repeat,那么您很有可能会与框架发生冲突。