herrh
herrh

Reputation: 1368

save scope value in another scope and display at the same time

I'm new too AngularJS and have a simple question.

I want to store the value from <input type="text" ng-model="abc"> into another scope called $scope.cde and display them both at the same time. At this time, only {{ abc }} is shown, but not {{ cde }}.

Why is this not working with this code? plnkr

HTML:

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

  <head>
    <script data-require="[email protected]" data-semver="1.2.7" src="http://code.angularjs.org/1.2.7/angular.js"></script>
    <script src="script.js"></script>
  </head>
  <body >
    <div ng-controller="ExampleCtrl">
      <h2>Scope Example</h2>
      <input type="text" ng-model="abc">
      <p>{{ abc }}</p>
      <p>{{ cde }}</p>
    </div>
  </body>

</html>

JS:

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

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

  $scope.cde = $scope.abc;

});

Upvotes: 0

Views: 113

Answers (2)

robe007
robe007

Reputation: 3947

You can use a directive with an isolated scope if you want:

html

<body >
 <div ng-controller="ExampleCtrl">
  <h2>Scope Example</h2>
  <input type="text" ng-model="abc" placeholder="enter stuff here" x-change:scope="cde">
  <p><strong>abc scope:</strong> {{ abc }}</p>
  <p><strong>cde scope:</strong> {{ cde }}</p>
 </div>
</body>

js

myApp.directive('changeScope', function () {

  var controller = ['$scope', function ($scope) {
    $scope.setValue= function(abc){
      $scope.cde = abc;
    }
  }];

  var component = function(scope, element, attrs) {       
    scope.$watch('abc', function (v) {
      scope.setValue(v);
    });
  }

  return {
    link:       component,
    controller: controller,
    // Isolated scope
    scope:  {
      abc:  '=ngModel',
      cde: '=changeScope'
    }
  };

});

Check the working plnkr !

Upvotes: 0

Andrii Iushchuk
Andrii Iushchuk

Reputation: 376

Use ng-change to do this

<input type="text" ng-model="abc" ng-change='cde = abc'>

Upvotes: 4

Related Questions