gpt4 book ai didi

javascript - 指令 Controller 显示错误

转载 作者:行者123 更新时间:2023-11-29 16:06:18 25 4
gpt4 key购买 nike

我打算只关注指令 Controller 的使用。因此,请回答与我假设的每个指令使用实例相同的错误,angular 将在指令中提到的 Controller 部分中出现一次。

//module declaration 
var app = angular.module('myApp',[]);

//controller declaration
app.controller('myCtrl',function($scope){
$scope.name = "Peter";
});

//app declaration
app.directive('myStudent',function(){
return{
template: "Hi! Dear!! {{name}}<br/>",
controller:function(scope, elem, attr){
console.log("controller");
}
}
});
<body ng-app="myApp" ng-controller="myCtrl"> 

<my-student></my-student>
<my-student></my-student>
<my-student></my-student>
<my-student></my-student>
<my-student></my-student>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script>
</body>

注意:

Kindly, throw light on error and on usage of directive controller only. I know same can be done by pre-link, post-link, or compile.

PS:我不明白一些外星天才的否决!

最佳答案

我觉得应该是链接函数而不是 Controller 。

//module declaration 
var app = angular.module('myApp', []);

//controller declaration
app.controller('myCtrl', function($scope) {
$scope.name = "Peter";
});

//app declaration
app.directive('myStudent', function() {
return {
template: "Hi! Dear!! {{name}}<br/>",
link: function(scope, elem, attr) {
console.log("controller");
}
}
});
<body ng-app="myApp" ng-controller="myCtrl">

<my-student></my-student>
<my-student></my-student>
<my-student></my-student>
<my-student></my-student>
<my-student></my-student>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script>
</body>

Best Practice: use controller when you want to expose an API to other directives. Otherwise use link.

Controller 接受一个数组:

var app = angular.module('myApp', []);

//controller declaration
app.controller('myCtrl', function($scope) {
$scope.name = "Peter";
});

//app declaration
app.directive('myStudent', function() {
return {
template: "Hi! Dear!! {{name}}<br/>",
controller: [
function(scope, elem, attr) {
console.log("controller");
}
]
}
});
<body ng-app="myApp" ng-controller="myCtrl">

<my-student></my-student>
<my-student></my-student>
<my-student></my-student>
<my-student></my-student>
<my-student></my-student>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script>
</body>

为了进一步阅读,我建议 angular documentation on directives

关于javascript - 指令 Controller 显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41135909/

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