3

HTML ページのテンプレートから div を表示および非表示にするのに問題があります。ここに簡単な JSFiddle の例を示します

  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>

表示または非表示にする div は html ページ全体であるため、こののように 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 に答える