Dea*_*ool 2 javascript angularjs
我打算只关注指令控制器的使用.所以,pl回答了我提到的每个指令用法实例所提到的相同错误,在指令中提到的控制器部分中,angular会出现一次.
//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");
}
}
});Run Code Online (Sandbox Code Playgroud)
<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> Run Code Online (Sandbox Code Playgroud)
注意:
请注意错误和使用指令控制器.我知道同样可以通过预链接,后链接或编译来完成.
PS:我不明白一些外星天才的投票结果!
我认为它应该是链接功能而不是控制器.
//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");
}
}
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
最佳实践:当您希望将API公开给其他指令时,请使用控制器.否则使用链接.
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");
}
]
}
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
为了进一步阅读,我建议有关指令的角度文档
| 归档时间: |
|
| 查看次数: |
41 次 |
| 最近记录: |