【问题标题】:How to tie ng-model variable to the value of an input box in angular?如何将 ng-model 变量与角度输入框的值联系起来?
【发布时间】:2015-09-24 03:57:58
【问题描述】:

没有任何角度,我有这样的输入(这是我想要的最终结果):

<input type="text" value="['Apple','Pear']">

我想要的是“值”中的内容来自范围变量。

$scope.mylist = ['Apple','Pear'] # Assume this is my controller

<input type="text" ng-model="mylist" value="">

这应该转化为我在顶部的内容。这是正确的方法吗?我怎样才能达到与我的第一个 sn-p 相同的效果? 如果将字符串构造为范围变量更容易,那也是可以接受的答案。我正在寻找简单的。

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    一个简单但不太好的解决方案是创建第二个变量(表示原始的 JSON 化),将其绑定到输入并观察更改并解析回原始变量。

    更好的解决方案是按照this 回答并创建一个指令来解析和格式化输入值。

    【讨论】:

    • 看是不是最有效率?如果可能的话,我想尽可能避免“观看”。虽然如果它涉及“单击按钮”然后将范围变量设置为某些东西,我更喜欢这样。
    【解决方案2】:

    我知道您曾评论说您想避免“观看”。请说说为什么?。我在指令中看到了 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

    【讨论】:

      猜你喜欢
      • 2014-01-11
      • 1970-01-01
      • 1970-01-01
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多