基于数组的多个输入
multiple inputs based on array
我的 angular 经验基本上是 3 天的兼职,所以我可能在这里遗漏了一些简单的东西。
我正在尝试创建一个基于数组的多个输入的动态列表,然后我想从应用程序的其他地方引用它。我尝试过的是从自定义指令加载模板,然后 $compile
-ing 它。
<input data-ng-repeat="term in query" data-ng-model="term">
我的控制器包含 $scope.query = [""]
,它成功创建了第一个空输入框。但是我修改的时候输入框好像没有更新$scope.query[0]
。这意味着当我尝试使用 $scope.query.push("");
创建另一个空输入框时(来自 keypress
正在寻找“/”键的侦听器)我收到 "duplicates not allowed" 错误。
我试过手动监听输入并根据它们的值更新 scope.$query
,但这感觉不太好 "angular",并导致奇怪的行为。
我需要做什么才能 link 这些值。我走对路了吗?
我制作了一个简单的 jsfiddle,展示了如何使用 angular 模型(服务)来存储数据。修改文本输入也会修改模型。为了在您的应用程序的其他地方引用它们,您可以在其他控制器中包含 TestModel
。
html:
<body ng-app="TestApp">
<div ng-controller="TestController">
<div ng-repeat="item in queries track by $index">
<input type="text" ng-model="queries[$index]" />
</div>
<br/><br/>
<button ng-click="getVal()">Get Values</button>
</div>
</body>
javascript:
var app = angular.module('TestApp',[]);
app.controller('TestController', function($scope, TestModel)
{
$scope.queries = TestModel.get();
$scope.getVal = function()
{
console.log(TestModel.get());
alert(TestModel.get());
}
});
app.service('TestModel', function()
{
var queries = ['box1','box2','box3'];
return {
get: function()
{
return queries;
}
}
});
我的 angular 经验基本上是 3 天的兼职,所以我可能在这里遗漏了一些简单的东西。
我正在尝试创建一个基于数组的多个输入的动态列表,然后我想从应用程序的其他地方引用它。我尝试过的是从自定义指令加载模板,然后 $compile
-ing 它。
<input data-ng-repeat="term in query" data-ng-model="term">
我的控制器包含 $scope.query = [""]
,它成功创建了第一个空输入框。但是我修改的时候输入框好像没有更新$scope.query[0]
。这意味着当我尝试使用 $scope.query.push("");
创建另一个空输入框时(来自 keypress
正在寻找“/”键的侦听器)我收到 "duplicates not allowed" 错误。
我试过手动监听输入并根据它们的值更新 scope.$query
,但这感觉不太好 "angular",并导致奇怪的行为。
我需要做什么才能 link 这些值。我走对路了吗?
我制作了一个简单的 jsfiddle,展示了如何使用 angular 模型(服务)来存储数据。修改文本输入也会修改模型。为了在您的应用程序的其他地方引用它们,您可以在其他控制器中包含 TestModel
。
html:
<body ng-app="TestApp">
<div ng-controller="TestController">
<div ng-repeat="item in queries track by $index">
<input type="text" ng-model="queries[$index]" />
</div>
<br/><br/>
<button ng-click="getVal()">Get Values</button>
</div>
</body>
javascript:
var app = angular.module('TestApp',[]);
app.controller('TestController', function($scope, TestModel)
{
$scope.queries = TestModel.get();
$scope.getVal = function()
{
console.log(TestModel.get());
alert(TestModel.get());
}
});
app.service('TestModel', function()
{
var queries = ['box1','box2','box3'];
return {
get: function()
{
return queries;
}
}
});