2

I did one reduced snippet of my problem. Actually I'm doing an app using ionic, but it doesn't matter, the problem occurs in the plunker too.

I've also read this answer and updated some of my code, but the problem persists.


I have this controller with an object:

app.controller('myCtrl', function($scope) {
  $scope.object = {
    boolean: true,
    btn1: 'Do it be TRUE',
    btn2: 'Do it be FALSE'
  }
})

And I want to change its boolean property inside this directive:

.directive('myDirective', function() {
  return {
    template: '<button class="btn btn-default">{{$obj.btn1}}</button>'
    + ' <button class="btn btn-default">{{$obj.btn2}}</button>',
    restrict: 'A',
    scope: { $obj: '=myDirective' },
    link: function(scope, element, attrs) {
      var listener = scope.$watch('$obj', function() {
        if (scope.$obj) listener();
        else return;

        var buttons = element.find('button'),
          btn1 = buttons.first(),
          btn2 = buttons.last();

        if(scope.$obj.boolean){
          btn1.addClass('selected');
          $('#Log').html('true');
        }else {
          btn2.addClass('selected');
          $('#Log').html('false');
        }

        buttons.on('click', function(){
          buttons.removeClass('selected');
          $(this).addClass('selected');

          var isTrue = this === btn1[0];
          $('#Log').html(String(isTrue)); // works
          scope.$obj.boolean = isTrue; // does not works
        });

      });
    }
  }
});

As you can see while running the plunker, the angular log does not update like the jQuery one, and I'm giving both the same value.

I am struggling with this by hours, any help would be really appreaciated, thanks for your time.

Community
  • 1
  • 1
Washington Guedes
  • 4,254
  • 3
  • 30
  • 56
  • As answered, you should REALLY be using ng-click for this and setting the Angular variable in scope, so you don't have to scope.$apply(). – Chris Stanley Apr 20 '16 at 15:01
  • @ChrisStanley. Do you mean `ng-click` in the template and `scope.myFunction` in the directive, right? I thought changing the value in the directive would be better because actually I have four pages that needs this directive, then I can declare the function only once inside the directive. What would be the best practice for this case? – Washington Guedes Apr 20 '16 at 15:16

1 Answers1

4

You shall notify angular that something has changed:

scope.$apply(function () { ... });

See plunker

P.S. use ng-click instead of jQuery click event.

karaxuna
  • 26,752
  • 13
  • 82
  • 117