Angularjs 如何将ng模型变量绑定到输入框的角度值?
没有任何角度,我有一个这样的输入,这是我想要的结果:Angularjs 如何将ng模型变量绑定到输入框的角度值?,angularjs,Angularjs,没有任何角度,我有一个这样的输入,这是我想要的结果: <input type="text" value="['Apple','Pear']"> 我希望值中的内容来自范围变量 $scope.mylist = ['Apple','Pear'] # Assume this is my controller <input type="text" ng-model="mylist" value=""> 这应该转化为我在顶部所拥有的。这样做对吗?如何实现与第一个代码片段相同的效
<input type="text" value="['Apple','Pear']">
我希望值中的内容来自范围变量
$scope.mylist = ['Apple','Pear'] # Assume this is my controller
<input type="text" ng-model="mylist" value="">
这应该转化为我在顶部所拥有的。这样做对吗?如何实现与第一个代码片段相同的效果?
如果将字符串构造为范围变量更容易,那么这也是一个可接受的答案。我正在寻找简单的解决方案。一个简单但不太好的解决方案是创建第二个变量来表示原始的JSONification,将其绑定到输入,观察更改并解析回原始
更好的解决方案是按照答案创建一个指令,用于解析和格式化输入值。我知道您已经评论说希望避免观看。请告诉我为什么?。我在指令中看到了watch的用法,因此我的解决方案如下
<div ng-app="myApp" ng-controller="myCtrl">
<div>
<input type="text" ng-model="newFruit">
<button ng-click="addFruit()">Add</button>
</div>
<input type="text" ng-allowed-vals="fruits" ng-model="fruit">
</div>
angular.module("myApp", []);
angular.module("myApp")
.controller("myCtrl", ["$scope", function($scope){
$scope.fruits = ["apple"];
$scope.fruit = "";
$scope.addFruit = function(){
$scope.fruits.push($scope.newFruit);
$scope.newFruit = "";
}
}]);
angular.module("myApp")
.directive("ngAllowedVals", [function () {
return {
restrict: "A",
require: "ngModel",
scope: {
ngAllowedVals: "="
},
link: function (scope, ele, attr, ngModelCtrl) {
scope.$watch("ngAllowedVals", function(old, val){
ngModelCtrl.$setViewValue(formatArr(scope.ngAllowedVals));
ngModelCtrl.$render();
}, true);
function formatArr(allowedVals){
if(!allowedVals.length) return "";
var result = "";
for(var i = 0; i < allowedVals.length; i++){
if(i < allowedVals.length - 1)
result += "'" + allowedVals[i] + "',";
else
result += "'" + allowedVals[i] + "'";
}
return "[" + result + "]";
}
}
}
}]);
看电视是最有效的吗?如果可能的话,我想尽量避免看电视。虽然如果它涉及到点击一个按钮,然后设置一个范围变量,我更喜欢这样。