2013-09-23 56 views

回答

1

我已經改變了你的代碼了一點,我通過指令的html標記傳遞user參數。

您可以在指令中包含使用scope屬性所需的許多其他參數。你可以在這裏讀更多關於它的內容。 (http://docs.angularjs.org/guide/directive

雖然你仍然需要使用$apply() - 不知道爲什麼你想「擺脫」它。在指令中使用$ digest/$ apply可以讓Angular知道你在異步調用或任何DOM操作之後做出了更改。

它沒有意義,你不應該在控制器內部使用它。

此外,你可以刪除jQuery操作(如果你想)使用更多的AngularJS方法與ng-class應用正確的類。 (http://docs.angularjs.org/api/ng.directive:ngClass

你可以看到一個工作普拉克這裏(http://plnkr.co/edit/MKmFLKpyAC87UbNaV0ef?p=preview

<!doctype html> 
<html ng-app="myApp"> 
<head> 
    <meta charset="utf-8"> 
</head> 
<style> 
    .active{ 
     color:red; 
    } 
</style> 
<body> 
<div ng-controller="myCtrl"> 
    <ul> 
     <li data-ng-repeat="user in ns.users"> 
      <div user="user" selected-user-box="{{user.id}}" class="box-select-user"> 
       <h2>{{user.name}}</h2> 
      </div> 
     </li> 
    </ul> 
    <b>{{ns.test}}</b> 
</div> 
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> 
    <script src="http://code.angularjs.org/1.0.8/angular.min.js"></script> 
    <script> 
     var app = angular.module('myApp', []); 
     app.factory('Users',function(){ 
      return [{id:1,name:'first'},{id:2,name:'second'},{id:3,name:'third'}] 
     }); 
     app.directive('selectedUserBox', function() { 
      return { 
       restrict: 'A', 
       replace: true, 
       scope: { 
        user: '=' 
       }, 
       template:'<h2>{{user.name}}</h2>', 
       link: function(scope, element, attrs) { 
        element.bind('click', function() { 
         $(this).parent().parent().find('div').removeClass('active'); 
         $('.box-select-user').removeClass('active'); 
         $(this).addClass('active'); 
        }); 
       }, 
      }; 
     }); 
     app.controller('myCtrl',function($scope,Users){ 
      $scope.ns = {}; 
      $scope.ns.users = Users; 
     }); 

    </script> 
</body> 
</html>