gpt4 book ai didi

angularjs - ngShow 无法在 HTML 上使用模板

转载 作者:搜寻专家 更新时间:2023-10-31 23:01:28 24 4
gpt4 key购买 nike

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

提前致谢

最佳答案

您需要使用 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 */
}
};
});

这将使它按预期工作!

Side note: You don't need to escape \" your double quotes since you have your template inside of a single quote ' <html here> ' string.

关于angularjs - ngShow 无法在 HTML 上使用模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29493351/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com