2014-11-17 97 views
1

我有一個這樣的控制器,它連接到html的body爲什麼dom事件在angularjs裏面的控制器裏面不起作用

angular.module("app", []) 

.controller("MyCtrl", function($scope) { 

    // Here I perform some jquery code listening for click event 

    $("a").click(function() { 
     $(this).toggleClass("active"); 
    }); 

}); 

現在,我想知道爲什麼這不起作用的控制器內。我知道,如果我將其納入指示,那麼它確實有效。

+2

你是什麼意思,它不起作用?更具體一點。 – Wawy

+0

不是直接的答案,但在我看來,DOM操作不應該在控制器內。這種方法有一些特定的目的嗎?就像你說的那樣,它在指令中起作用。 – zvona

+0

我想你應該再讀一遍AngularJs控制器。你定義的那個函數被用作構造函數 –

回答

1

Don't mix up JQuery with AngularJS,因爲它不是一個好的做法,

如果你想要一些切換功能使用內置ngClick指令功能,通過AngularJs提供的,而不是使用JQuery$("a").click

Sample Demo 1

Sample Demo 2

Sample Demo 3

Sample Demo 4

function MainController($scope) { 
 
    $scope.toggle = true; 
 
}
.box { 
 
    color: white; 
 
    text-align: center; 
 
    height: 100px; 
 
    font-size: 86px; 
 
} 
 
.on { 
 
    background-color: green; 
 
} 
 
.off { 
 
    background-color: red; 
 
} 
 
.box-show-setup, 
 
.box-hide-setup { 
 
    -webkit-transition: all linear 0.3s; 
 
    -moz-transition: all linear 0.3s; 
 
    -ms-transition: all linear 0.3s; 
 
    -o-transition: all linear 0.3s; 
 
    transition: all linear 0.3s; 
 
} 
 
.box-show-setup { 
 
    opacity: 0; 
 
    height: 0; 
 
} 
 
.box-show-setup.box-show-start { 
 
    opacity: 1; 
 
    height: 100px; 
 
} 
 
.box-hide-setup { 
 
    opacity: 1; 
 
    height: 0; 
 
} 
 
.box-hide-setup.box-hide-start { 
 
    opacity: 0; 
 
    height: 100px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app ng-controller="MainController"> 
 
    <button ng-click="toggle = !toggle">Toggle!</button> 
 

 
    <div class="box on" ng-show="toggle" ng-animate="'box'">On</div> 
 
    <div class="box off" ng-hide="toggle" ng-animate="'box'">Off</div> 
 
</div>

又讀這個美麗的東西

Using AngularJS? Stop using jQuery as a crutch.

相關問題