0

I have 2 templates in ionic that have the same ng-controller. In the first template, I'm able to call {{answer}} that is declared in the function, but when I try to call it in the second template it doesn't show.

Here are the sample code:

1st. Template

<ion-view view-title="calculator" ng-controller="calcCtrl">
<input type="number" ng-model="num1">
<input type="number" ng-model="num2">
<button class="button button-block button-positive" ng-click="addition(num1, num2)">
  Add
</button>
<h2>Answer: {{answer}}</h2>

2nd. Template

<ion-view view-title="Add" ng-controller="calcCtrl">
   {{answer}}
</ion-view>

JS file:

app.controller("calcCtrl", function($scope) {
  $scope.addition = function(num1, num2) {
    $scope.answer = num1 + num2;
  }
});

How can I call the output for {{answer}} in my 2nd. template?

16
  • did you want to see the result on same time or after click and route on template 2 ? Commented Jul 4, 2016 at 4:04
  • after click and route to template 2 Commented Jul 4, 2016 at 4:15
  • in this case are you sure your scope already exist to bind in another template? Commented Jul 4, 2016 at 4:16
  • 1
    @hazimIskandar In your case, when you route to template2, controller is reinitialized hence you can't see the answer. Commented Jul 4, 2016 at 4:20
  • 1
    u have to pass the num1 and num2 to the template2 with out that how it will be work Commented Jul 4, 2016 at 4:21

1 Answer 1

1

I think you are very close to get the answer. The problem is in your controller you have not defined $scope. answer Just make this correction and try now.....

enter code here

app.controller("calcCtrl", function($scope) {
  $scope.answer=0;
  $scope.addition = function(num1, num2) {
    $scope.answer = num1 + num2;
  }
});

Now when the value of answer will be changed it will be updated in DOM.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.