ngShow无法在HTML上使用模板

时间:2015-04-07 13:56:13

标签: angularjs html5 angularjs-directive ng-show angularjs-ng-show

我有一个问题是在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代码添加到模板中,就像在此example中一样,因为我要显示或隐藏的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;
    };
        }
    };
});

提前致谢

2 个答案:

答案 0 :(得分:3)

如果您希望在transclusion中包含某些内容,则需要使用<example> <!-- this stuff here --> </example>,一旦编译并创建了该指令,就会显示。

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

<强> jsFiddle demo

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> '内的模板   字符串。

答案 1 :(得分:2)

你可以这样做 - Fiddle

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>