【问题标题】:angular-directive - jQuery click event not updating the scopeangular-directive - jQuery 点击事件不更新范围
【发布时间】:2016-09-27 04:47:38
【问题描述】:

在指令中,单击 jQuery 元素时,我正在更新范围。但它不起作用。这样做的正确方法是什么?

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

【问题讨论】:

    标签: jquery angularjs angular-directive


    【解决方案1】:

    试试这个使用scope.$apply或者为了更好的性能使用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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-25
      • 2013-03-11
      • 1970-01-01
      • 2011-11-23
      • 2018-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多