0

Is it possible to bind the value of an input to the value of another input? The following is not working:

<input ng-model="val">
<input value="Hello {{val}}">
1
  • What is not working? It seems to work for me. Commented Nov 4, 2013 at 10:45

3 Answers 3

2

Here is simple solution: http://plnkr.co/edit/7HxnM3O1UE1RxCCPvvJ0?p=preview

app.js

app.controller('MainCtrl', function($scope) {
    $scope.formatText = function() {
        return "Hello " + $scope.text;
    };

    $scope.$watch('text', function(newValue) {
        $scope.formatedText = "Hello "+ (newValue ? newValue : "");
    })
});

index.html

<body ng-controller="MainCtrl">
    <input type="text" ng-model="text"/>
    <input type="text" ng-model="formatedText"/>
</body>

For more common way you can use $scope.$eval together with your own directive.

Sign up to request clarification or add additional context in comments.

Comments

1

For your simple use case you posted you can use dot notation.

Fiddle example Fiddle

<input ng-model="new.val">
<input value="Hello {{new.val}}">

By using dot.notation you avoid collision with scoping issues and conflict with global namespace. Not knowing all the variables involved this might have been the issue.

Anything $scope.val would interfere.

<input ng-model="val">
<input value="Hello {{val}}">

By using dot notation and deep linking you can avoid a lot of common issues.

2 Comments

The OPs code works as is. What advantage to you get from using dot notation?
Added more explanation. With limited info I tried posting a common issue I've seen.
0

Yes. Here is a working plunker with your code.

js:

var myApp = angular.module('myApp', []);


myApp.controller('Ctrl', function($scope) {

  $scope.val = 'Guy';

  });

html:

<!DOCTYPE html>
<html ng-app="myApp">

  <head>
    <script data-require="angular.js@*" data-semver="1.2.0-rc3-nonmin" src="http://code.angularjs.org/1.2.0-rc.3/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="Ctrl">
    <h1>Hello Plunker!</h1>

    <input ng-model="val">
    <input value="Hello {{val}}">
  </body>

</html>

*Note: you aren't required to add val to the controller unless you want to initialize its value.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.