Mário Souto Mário Souto - 1 month ago 5
AngularJS Question

button toggle not working with angularjs

I'm trying to simply change the button text with a toggle but im failing to do so idk why. I'm new to angular so bare with me. The button only shows 'ver fotos' and doesnt change to my 2nd option. Maybe i can't put two ng-click like that? This is my code:



angular.module('app.controllers', [])
.controller('perfilCtrl', ['$scope', '$stateParams', "detailService",// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams, detailService) {
$scope.detalhes=detailService.data;
$scope.goEsconder = false;
$scope.toggle = true;
$scope.$watch('toggle', function(){
$scope.toggleText = $scope.toggle ? 'Ver fotos' : 'Ver características';
})

}])

<ion-view id="page4">
<ion-content padding="true" class="backg">
<div class="row">
<div class="col">
<h3 class="name">{{detalhes[0]}}</h3>
</div>
</div>
<div class="row">
<div class="col">
<p class="descricao">{{detalhes[2]}}</p>
</div>
</div>
<div class="row">
<div class="col text-center" ui-sref="contacto"><button class="button b2">
Contactar
</button>
</div>
<div class="col text-center"><button class="button b3" ng-click="goEsconder = !goEsconder; toggle = !toggle">
{{toggleText}}
</button>
</div>
</div>




Answer

Use an object so that child scopes will use inheritance. There is no inheritance on primitives in javascript.

So what happens is you are only changing the primitive in the child scope and that change is hidden from the parent so the watch won't fire

  $scope.myModel = { toggle: true };
  $scope.$watch('myModel.toggle', function(nVal, oVal) {
    $scope.toggleText = $scope.myModel.toggle ? 'Ver fotos' : 'Ver características';
  });

HTML

<button class="button b3" ng-click="myModel.toggle = !myModel.toggle">
  {{toggleText}}
</button>

DEMO

Comments