gpt4 book ai didi

javascript - 在简单的指令示例中嵌入用法

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:01:29 24 4
gpt4 key购买 nike

在下面的简单示例中,我通过 View 上的指令从 Controller 打印名称模型。该示例运行良好,但我不明白 transclude 的用途是什么。有人可以解释它的用法吗?

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js" ></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<people></people>

<script>
//module declaration
var app = angular.module("myApp",[]);
//controller declaration
app.controller('myCtrl',function($scope){
$scope.name = "Peter";
});
//directives declaration
app.directive('people',function(){
return{
restric: 'E',
template: '<div>{{name}}</div>',
transclude: true
}
});

</script>
</body>
</html>

最佳答案

您的代码并没有真正展示 transclude 的作用:查看这个 plunk 并更改 true/false 值:

Plunk

希望您现在会注意到效果。来自 plunkr 的源代码,有一些修改。

<!DOCTYPE html>
<html>

<head>
<script data-require="angular.js@1.5.3" data-semver="1.5.3" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>

<body ng-app="myApp" ng-controller="myCtrl">
<people>HI there</people>

<script>
//module declaration
var app = angular.module("myApp",[]);
//controller declaration
app.controller('myCtrl',function($scope){
$scope.name = "Peter";
});
//directives declaration
app.directive('people',function(){
return{
restric: 'E',
template: '<div><ng-transclude></ng-transclude>: {{name}}</div>',
transclude: false
}
});

</script>
</body>

</html>

所以当它为真时,你会看到内容被嵌入了,

所以它说你好:彼得

当为 False 时,它​​会删除那里的 HI,但保留名称和我的冒号:

: 彼得

关于javascript - 在简单的指令示例中嵌入用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36884156/

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