1

I have a string like var message = "you are moving to {{output.number}}";

I want this to be put to div element. i tried using $("#message").html(message);

but it just printed the whole string for me. I want to have the output.number print the value it had. Is it possible to achieve what i want?

I am using angular.js 1.5.

6 Answers6

1

I hope you are looking for something like this. You can do it by using the scope variable inside the controller.

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.bootcss.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<body>

    <div ng-app="myApp" ng-controller="myCtrl">
        <input type="number" ng-model="output.number" />
        <button ng-click="AppendItem()">Append</button>
        <div id="message"></div>
    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope) {
            $scope.output = {};
            $scope.AppendItem = function () {
                var string = "Your Number is " + $scope.output.number;
                $("#message").html(string);
            }
        });
    </script>

</body>

</html>
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
1

Use $interpolate service like:

var message = $interpolate("you are moving to {{number}}")(output) 
// or
var message = $interpolate("you are moving to {{output.number}}")($scope)
Matuszew
  • 841
  • 5
  • 12
0

You are almost there just try :

$scope.output.number = '123';
var message = "you are moving to" + output.number;
$("#message").html(message);

Don't put variable inside "" quotes.

Jenny
  • 663
  • 4
  • 8
0

When we are going to append a string variable to another string variable then we need to use append operator ie., "+". Here is an example.

var output.number = 10;
var message = "you are moving to " + output.number;
$("#message").html(message);
Dimple
  • 173
  • 2
  • 13
0

You can do like this using $compile:

$compile(angular.element(document.querySelectorAll('#message')[0]).html("you are moving to {{output.number}}"))($scope);

Add $compile as dependency in your controller.

All the best.

Sai M.
  • 2,548
  • 4
  • 29
  • 46
0

You can try this:

<html ng-app="app">
 <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
 </head>
 <body ng-controller="appCtrl">
  <p id="message"></p>
  <script src="https://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"> </script>

</body>

JS:

Should not write DOM Manipulation code inside controller, but can get the idea how to do it.

var app = angular.module('app', []);
app.controller('appCtrl', function($scope, $interpolate){
  var msg = "you are moving to {{number}}";
  $scope.number = 10;
  $('#message').html($interpolate(msg)($scope));
});
Jyoti Prakash
  • 1,180
  • 8
  • 9