Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS, how to bind a variable to concatenation of two other bound variables?

Tags:

angularjs

I am new to AngularJS and trying to build an AngularJS practice app, in which, the user will concatenate a url from multiple inputs, i.e. protocol, domain, path, param1, param2, param3... etc.

And the app will create a link to the url:

<a>{{protocol}}://{{domain}}{{path}}?{{param1}}&{{param2}}&{{param3}}</a>

Above url is used twice. Once on the href attribute, as well as the actual text. Now what I want to do is something like:

<a href="{{url}}">{{url}}</a>

But I am not sure where to assign url. I tried below, and it worked, but doesn't seem correct.

<a href='{{url = protocol+"://"+domain+path+"?"+param1+"&"+param2+"&"+param3}}'>{{url}}</a>

Assuming that url is used many times in the app, where would be the most appropriate place to assign url?

like image 898
haejeong87 Avatar asked Aug 12 '13 09:08

haejeong87


1 Answers

You shouldn't assign scope variables in the view (the HTML) - it's only for reading them.

To make a new variable from inputs, add a ng-model to each of them and then in the controller define a method that makes a $scope variable from them e.g.

Your HTML form:

<div ng-controller="MyCtrl">

    <input type="text" ng-model="urlParts.protocol">
    <input type="text" ng-model="urlParts.domain">
    <!-- etc -->
    <a ng-href="{{makeUrl()}}">{{makeUrl()}}</a>
</div>

JS:

function MyCtrl($scope) {
    $scope.urlParts = {};
    $scope.urlParts.protocol = ""; 
    $scope.urlParts.domain = ""; 
    // etc... 
    // These values will be updated when the user types in the input boxes

    $scope.makeUrl = function() {
      return $scope.urlParts.protocol + "://" + $scope.urlParts.domain + $scope.urlParts.path + "?" + $scope.urlParts.param1 + "&" + $scope.urlParts.param2 + "&" + $scope.urlParts.param3;
    }
}
like image 113
Michael Low Avatar answered Sep 29 '22 12:09

Michael Low