Javascript 在angularjs的指令中使用'require'
在角度指令中使用require时出错 这是我的html:Javascript 在angularjs的指令中使用'require',javascript,angularjs,angular-directive,Javascript,Angularjs,Angular Directive,在角度指令中使用require时出错 这是我的html: <!doctype html> <html ng-app="myApp"> <head> <title>Page Title</title> <meta charset="UTF-8"> <meta name="viewport" content="initial-scale=1.0">
<!doctype html>
<html ng-app="myApp">
<head>
<title>Page Title</title>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.4.2/angular-ui-router.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<superman speed>This is a superhero</superman>
</body>
</html>
我得到的错误是supermanCtrl.addspeed()不是函数。
我还记录了我的supermanCtrl,它不包含addspeed功能。任何有关发生这种情况的细节。
感谢将控制器的上下文作为链接函数的第四个参数注入。它不注入$scope
对象
从文档中:
要求
需要另一个指令并将其控制器作为第四个参数注入链接函数
使用指令控制器的此
上下文定义控制器方法:
angular.module("myApp").directive('superman',function(){
return{
restrict:'E',
controller:function($scope){
$scope.abilities=[];
$scope.addspeed=function(){
$scope.abilities.push('Speed');
}
//-------------------------------
//USE `this` context
this.addspeed = $scope.addspeed;
//-------------------------------
},
link:function(scope,element,attrs){
element.bind('mouseenter',function(){
console.log(scope.abilities);
})
}
}
})
假设我们有大量的函数,所以我们必须这样做。addspeed=$scope.addspeed;每次都是。有没有更短的路
如果不需要$scope
上的函数,只需直接绑定到this
属性:
angular.module("myApp").directive('superman',function(){
return{
restrict:'E',
controller:function($scope){
$scope.abilities=[];
//$scope.addspeed=function(){
//BIND directly to the `this` property
this.addspeed = function() {
$scope.abilities.push('Speed');
}
},
link:function(scope,element,attrs){
element.bind('mouseenter',function(){
console.log(scope.abilities);
})
}
}
})
谢谢,但是还有一个小问题,假设我们有很多函数,所以我们必须这样做;每次都是。有没有更短的路?我不知道这是否有意义
myApp.directive('speed',function(){
return {
require:'superman',
link:function(scope,element,attrs,supermanCtrl){
supermanCtrl.addspeed();
}
}
})
angular.module("myApp").directive('superman',function(){
return{
restrict:'E',
controller:function($scope){
$scope.abilities=[];
//$scope.addspeed=function(){
//BIND directly to the `this` property
this.addspeed = function() {
$scope.abilities.push('Speed');
}
},
link:function(scope,element,attrs){
element.bind('mouseenter',function(){
console.log(scope.abilities);
})
}
}
})