3

我在 HTML 页面上的模板中显示和隐藏 div 时遇到问题。这是一个简单的 JSFiddle 示例Example

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

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

HTML是这样的:

<body ng-app="demo" ng-controller="exampleController">
<div>
    <div ng-controller="exampleController as ctrl">
        <example example-attr="xxx">
            <p ng-show="showMe">Text to show</p>
        </example>
    </div>
</div>

我不能像在这个例子中那样将我的 html 代码添加到模板中,因为我想要显示或隐藏的 div 是整个 html 页面。

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

提前致谢

4

2 回答 2

3

transclusion如果您想在您的 , 中包含某些内容,则需要在<example> <!-- this stuff here --> </example>编译和创建指令后显示出来。

scope: {}在您的指令中获取对象。

jsFiddle 演示

app.directive('example', function () {
    return {
        restrict: 'E',

        template: '<div ng-transclude></div><button ng-click="clickMe()">Click me</button>',

        // ^ notice the ng-transclude here, you can place this wherever 
        //you want that HTML to show up

        // scope : {}, <-- remove this
        transclude: true, // <--- transclusion

        // transclude is a "fancy" word for, put those things that are 
        // located inside the directive html inside of the template 
        //at a given location

        link: function (scope) {
            /* this remains the same */
        }
    };
});

这将使它按预期工作!

旁注:您不需要转义 \"双引号,因为您的模板位于single quote ' <html here> ' 字符串中。

于 2015-04-07T14:13:37.420 回答
2

你可以这样做 -小提琴

JS

var app = angular.module("demo", [])

app.controller('exampleController', function ($scope) {
    $scope.showMe = false;
});

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

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

标记

<body ng-app="demo" ng-controller="exampleController">
    <div>
        <div ng-controller="exampleController as ctrl">
            <example example-attr="xxx" show-me="showMe"></example>
            <p ng-show="showMe">Text to show</p>
        </div>
    </div>
</body>
于 2015-04-07T14:10:16.820 回答