angularjs指令中的Ng-model
ng-model in angularjs directive
我试图创建一个指令,将创建不同类型和不同数字的输入(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,那么您很有可能会与框架发生冲突。
相关文章:
- 在指令中使用 ng-model 和 ng-repeat
- AngularJS - 指令填充文本框,但ng-model没有值
- 将 md-dialog 中的值绑定到指令中的 ng-model
- AngularJS - 不能使用指令在ng-model中引用$index
- AngularJS - 在带有重复和动态 html 控件的指令中使用 ng-model
- AngularJs 指令在更改时获取单选按钮 ng-model 值
- Angular$scope$注意仅从表单(ng-model指令)更改的变量
- 在Angularjs中,嵌套在指令中的控制器可以设置指令的ng-model
- 使用ng-model, bindToController在一个页面上显示多个指令
- angularjs指令中的Ng-model
- Ng-repeat使用键和值,然后使用键作为ng-model的指令值
- 在IE9和ie10中,angularjs的ng-change不会触发ng-model-onblur指令
- 创建一个使用ng-model并具有唯一作用域的指令
- 如何创建一个使用ng-model的angular数据提取器指令
- Angularjs的ng-model在使用自定义指令后无法工作
- 带ng-model不绑定的Angular指令
- Angular js、ng-model还没有为第三方指令做好准备
- 从指令链接函数内部访问ng-model
- Ng-model在嵌套指令中没有更新
- Angular自定义指令不能将value更改为ng-model