ng-show在指令模板中不起作用

时间:2014-08-27 22:49:03

标签: angularjs angularjs-directive ng-show

我想做这样的事情 fiddle,使文字消失,每次点击都会重新出现。

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

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

这是正确的方法还是有更优雅的方法?

3 个答案:

答案 0 :(得分:5)

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

将您的点击处理程序放在链接功能中,并将showMe公开给scope

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 :(得分: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,因为在表达式求值为true之前,它不会在DOM中呈现元素。

答案 2 :(得分:0)

您可以通过设置scope:false隐藏指令中的范围 然后,您可以将所有功能放在主控制器范围

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;
    };
}]);

希望这有帮助

相关问题