2014-08-27 74 views
3

我想要做这样的事情,如 fiddle,使文本消失并随着每次点击而重新出现。ng-show无法在指令模板中工作

问题是,在隔离范围内,您似乎无法访问控制器范围。我解决了它的连接功能,处理有点击事件,并使用范围设置,我的“SHOWME”标志$适用,如:

scope.$apply('showMe = false'); 

这是正确的方式去还是有一些更优雅的方法?

回答

5

在这里你去(http://jsfiddle.net/66d0t7k0/1/

把你的点击处理程序的链接功能和揭露showMescope

app.directive('example', function() { 

    return { 
     restrict: 'E', 
     template: '<p ng-show=\"showMe\">Text to show</p><button ng-click=\"clickMe()\">Click me</button>', 
     scope: { 
      exampleAttr: '@' 
     }, 
     link: function (scope) { 
      scope.clickMe = function() { 
       scope.showMe = !scope.showMe; 
      }; 
     } 
    }; 
}); 
1

要扩大apairet的答案,因为你的指令,可使用孤立的范围,你可以处理模板本身的所有内容,如下所示:

app.directive('example', function() { 

    return { 
     restrict: 'E', 
     template: '<p ng-show=\"showMe\">Text to show</p><button ng-init=\"showMe = false\" ng-click=\"showMe = !showMe\">Click me</button>', 
     scope: { 
      exampleAttr: '@' 
     }, 
     link: function (scope) { 

     } 
    }; 
}); 

另一个考虑因素是使用ng-if而不是ng-show,因为它不会在DOM中呈现元素,直到表达式求值为true。

0

您可以通过设置范围躲在指令范围:假 然后你可以把你所有的功能在主控制器范围

angular.module('appMyApp').directive('appMyAppItem', function() { 
    return { 
     transclude: true, 
     templateUrl: 'link/to/url', 
     controller: 'appMyAppController', 
     scope: false 
    } 
}); 


angular.module('appMyApp').controller('appMyAppController', ['$scope', function($scope){ 

    $scope.showItem = true; 
    $scope.toggleItem = function(){ 
     $scope.showItem = !$scope.showItem; 
    }; 
}]); 

希望这有助于

相关问题