0

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

1 Answer 1

1

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>

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.