2017-03-01 53 views
0

在以下單擊div的示例中,背景必須更改爲黃色。沒有發生,也沒有給出錯誤。 Pl,解釋爲什麼!單擊後指示背景不變(通過事件綁定)

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

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

 
//directive declaration 
 
app.directive('myStudent', function(){ 
 
\t return{ 
 
\t \t template:"<div style='width:200px;height:200px;'>Hi my friend!</div>", 
 
\t \t link: function(scope, elem, attrs){ 
 
\t \t \t elem.bind('click',function(){ 
 
\t \t \t \t elem.css("background","yellow"); 
 

 
\t \t \t }); 
 
\t \t } 
 
\t } 
 
});
<body ng-app="myApp" ng-controller="myCtrl"> 
 

 
{{name}}<br/> 
 
<my-student></my-student> 
 

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

回答

3

當您創建從一個元素的指令,你必須記住,新創建的元素使用thew以下默認顯示類型:

display: inline; 

並由此,有一個0px的高度。

您可以通過簡單添加display:block;該指令元素:

<my-student style="display: block;"></my-student> 

或使用屬性創建指令:

<div my-student></div> 

下面是一個更新的例子:

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

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

 
//directive declaration 
 
app.directive('myStudent', function(){ 
 
\t return{ 
 
\t \t template:"<div style='width:200px;height:200px;'>Hi my friend!</div>", 
 
\t \t link: function(scope, elem, attrs){ 
 
\t \t \t elem.bind('click',function(){ 
 
\t \t \t \t elem.css("background","yellow"); 
 

 
\t \t \t }); 
 
\t \t } 
 
\t } 
 
});
<body ng-app="myApp" ng-controller="myCtrl"> 
 

 
{{name}}<br/> 
 
<my-student style="display: block;"></my-student> 
 

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

在任何情況下,我會建議你堅持角ng-cli對於這種交互CK指令,在下面的例子:

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

 
app.controller('myCtrl',function($scope){ 
 
\t $scope.name = 'Peter'; 
 
}); 
 

 
app.directive('myStudent', function(){ 
 
\t return{ 
 
\t \t template:"<div ng-click='changeBackground()' style='height:200px;' ng-style='divStyle'>Hi my friend!</div>", 
 
\t \t link: function(scope, elem, attrs){ 
 
     scope.changeBackground =() => { 
 
     scope.divStyle = { backgroundColor: 'yellow' } 
 
     } 
 
\t \t } 
 
\t } 
 
});
<body ng-app="myApp" ng-controller="myCtrl"> 
 

 
{{name}}<br/> 
 
<div my-student></div> 
 

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