如何将ng-model变量与angular中的输入框的值绑定? [英] How to tie ng-model variable to the value of an input box in angular?

查看:40
本文介绍了如何将ng-model变量与angular中的输入框的值绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Without any angular, I have an input like this (which is the end result of what I want):

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

我想要的是值"中的内容来自范围变量.

What I want is the content in "value" to come from a scope variable.

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

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

应该翻译成我最顶部的内容.这是正确的方法吗?如何实现与第一个片段相同的效果?如果将字符串构造为作用域变量比较容易,那么这也是可以接受的答案.我正在寻找简单的东西.

Which should translate to what I have at the top. Is this the right way to do this? How can I accomplish the same effect as my first snippet? If it is easier to just construct a string as a scope variable, that is also an acceptable answer. I am looking for simple.

推荐答案

我知道您已发表评论说要避免观看".请告诉为什么?我已经在指令中看到了watch的用法,因此我的解决方案如下.

I know you have commented saying you want to avoid "watch". Please tell why?. I have seen usage of watch in the directives hence my solution is as below.

<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

这篇关于如何将ng-model变量与angular中的输入框的值绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆