user2024080 user2024080 - 6 months ago 32
jQuery Question

angular-directive - jQuery click event not updating the scope

In the directive, On click of jQuery element, i am updating the scope. But it's not working. what is the correct way to do this?

angular.module('app.directives', []).directive('newContent', function() {

return {

link: function(scope, element, attrs) {

var title = element.find('h1'); //getting the element
scope.show = true;

var that = scope;

title.on('click', function(){

scope.show = false; //not working

})

}

}

})


Live Demo

SSH SSH
Answer

try this use scope.$apply or for better performancce use scope.$evalAsync

  scope.$apply(function(){
         scope.show = false;
    })

var appModules = ['app.directives']

var app = angular.module('plunker', appModules);


app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
});



angular.module('app.directives', []).directive('newContent', function() {

  return {

    link: function(scope, element, attrs) {
      
      var title = element.find('h1');
      scope.show = true;
      
      var that = scope;

      title.on('click', function(){
       
     scope.$evalAsync(function() {
         scope.show = false;
      );
     })

    }

  }

})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="plunker" ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    
    <div class="content" my-content>
      <h1>My Content</h1>
    </div>
    
     <div class="content" new-content>
       <h1>click me</h1>
      <h2 ng-show="show">My Content</h2>
    </div>
    
  </div>