0

I'm writing a program to display the text from the text-box to a box. This is done using angular js. I'm stuck at the portion where, i can't pass the value from one controller to another. Here's the code :

<html ng-app="MyApp">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
<script data-require="angular.js@1.1.x" src="http://code.angularjs.org/1.1.5/angular.min.js" data-semver="1.1.5"></script>
<script src="app.js"></script>
</head>

<body>
<div class="container">
<div class="box" ng-controller="OutputController">
       {{output.text}}
</div>

<div class="row" ng-controller="InputController">
  <input class="input-text" ng-model="output.text">
  <button class="btnoutput btn-primary" ng-click="onClick()">Click</button>
</div>
</div>    
</body>

</html> 

JS:-

angular.module("MyApp",[]);

var application = angular.module("MyApp");

// Input
angular.module("MyApp").controller("InputController",function($scope,Share){
  //$scope.output = Share;
  $scope.onClick = function(){
  $scope.output.text = "Hello " ;
 }
});



// Output
angular.module("MyApp").controller("OutputController",function($scope,Share){
  $scope.output = Share;
});



// Share the data
angular.module("MyApp").factory("Share",function(){
  var object = {};
  object.text = "";
  return object;
});

Until now, the value is getting displayed inside the box, while i type.That is at the same time. But i want to display the text only when i click the button. Thank You

Utopik
  • 3,783
  • 1
  • 21
  • 24
  • @Stewie The functions are written in different way there. I'm a beginner, so i don't know much about angular js. –  Jun 28 '13 at 14:24
  • 1
    `Tip:` you declare the `application` variable but never use it. Try replacing `angular.module("MyApp")` by this same variable. – Édouard Lopez Jun 28 '13 at 15:06

1 Answers1

2

In the scope of the InputController, your ng-model on the input tag is directly bound to the service that you use to share the data between the controllers.

Create a different model on the input. So, in your example, you can have a model like:

<input class="input-text" ng-model="inputText">

Inside the InputController function, you can then pass the data in the model attached to the input tag to the service after click. Using your example, this should look like:

$scope.onClick = function () {
    $scope.output.text = $scope.inputText ;
}

This way, as you type inside the input box, the data is stored in a different model and it is updated in OutputController only when you click the button in the scope of InputController.

callmekatootie
  • 10,989
  • 15
  • 69
  • 104