在没有任何角度的情况下,我有一个这样的输入(这是我想要的最终结果):
<input type="text" value="['Apple','Pear']">我想要的是"value“中的内容来自作用域变量。
$scope.mylist = ['Apple','Pear'] # Assume this is my controller
<input type="text" ng-model="mylist" value="">这应该可以转化为我在顶部的东西。这是正确的方法吗?如何才能达到与第一个代码片段相同的效果?如果只将字符串构造为作用域变量更容易,那么这也是一个可以接受的答案。我正在寻找简单。
发布于 2015-09-24 12:00:00
一个简单但不太好的解决方案是创建第二个变量(表示原始变量的JSONification ),将其绑定到输入并观察更改,然后解析回原始变量。
更好的解决方案是遵循this answer并创建一个用于解析和格式化输入值的指令。
发布于 2015-09-24 16:29:13
我知道你已经评论说你想避免“看”。请告诉我为什么?我在指令中看到了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 + "]";
}
}
}
}]);JSFiddle
https://stackoverflow.com/questions/32753082
复制相似问题