2017-03-01 8 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> 

または属性を使用してディレクティブを作成:ディレクティブ要素に私は、いずれの場合においても

//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>

<div my-student></div> 

ここで更新例ですあなたは角に固執することをお勧めします

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>

:この種の相互作用のためのCKディレクティブは、以下の例を見つけます
関連する問題