简体   繁体   中英

How to change my Angularjs $scope to accept a JavaScript variable type string

I have the following angularjs scope that:

$scope.Zips = {};

Is there a way for my angularjs scope to accept a variable that is a string? I would like to retrieve my string (that is a list) in the following function:

$scope.GetCurrentZip = function (){
    try{
        $scope.Zips = $parse(getZipCodes());
    } catch(err) {

    }
}

The following is the function in JavaScript that retrieves the list of Zip Codes:

function getZipCodes() {
        var miles = document.getElementById("miles").options[document.getElementById("miles").selectedIndex].innerHTML;
        var zip = document.getElementById("zip").value;
        var zips_within_radius = document.getElementById("zipsWithinRadius");
        // debugger;
        if (typeof zip === 'undefined' || typeof miles === 'undefined' || !zip.length || !miles.length) return false;

    var zips = getZips();
        var zip_list = "";
    if (zips.length) {
            zip_list = zips.join();
            zips_within_radius.value = zip_list;
    }
        return zip_list;
  }

Image on what I am seeing:

在此处输入图片说明

The issue I am having is in my form, I have the following:

<input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5"
       ng-model="searchParam.Zip" placeholder="Zip code" type="text" />

I would like the ng-model="searchParam.Zip" to retrieve the list I am getting from the list instead from the user input.

I think what @FrankModica is saying is, if you need to store an array of zips (strings) in your scope, you can do that rather than thinking of it as a JSON object:

$scope.Zips = [];

Have getZipCodes() return an array and you get what it seems you're looking for.

If you want to keep getZipCodes() the way you have it, then just declare the var without a type or as an empty string:

$scope.Zips;
$scope.Zips = '';

You may want to reconsider passing the value into the $scope as a single string, but if that really works for your use case there you go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM