2017-07-15 10 views
0

ここに私のHTMLコードが入ります。子ディレクティブに基づいてDOMを操作する属性 - angularJs

<parent> 
    <div idx=2>DIV - 3</div> 
    <div idx=0>DIV - 1</div> 
    <div idx=1>DIV - 2</div> 
</parent> 

ディレクティブの属性に基づいて子divを並べ替える必要があります。ここで私のangularjsコードに行く。 idxの値に基づいて、私はDOMを操作したい。

app.directive('parent', function() { 
    return { 
     restrict: 'E' 
    } 
}); 
app.directive('idx', function() { 
    function link(scope, element, attrs) { 
     console.log(scope.idx); 
    } 
    return { 
     restrict: 'A', 
     scope: { 
      idx: '=' 
     }, 
     link: link 
    } 
}); 

私はangularjsを初めて利用しています。私を助けてください、またはこれを達成するためのヒントを提供してください。

答えて

0

これはちょっと難しいです。私はこれを達成するための提案をしています。配列変数(idxでソート)を$scopeに作成し、ng-repeatを使用してすべての子をバインドします。次のコードを試してください。期待どおりに動作するはずです。

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

 
app.controller("MainCtrl", ["$scope", function($scope) { 
 
    $scope.indexes = [ 
 
    {key: 2, value: 3}, 
 
    {key: 0, value: 1}, 
 
    {key: 1, value: 2} 
 
    ]; 
 
    
 
    $scope.indexes.sort(function(a, b) { 
 
    return a.key > b.key; 
 
    }); 
 
}]); 
 

 
app.directive("parent", function() { 
 
    return { 
 
     restrict: "E" 
 
    } 
 
}); 
 

 
app.directive("idx", function() { 
 
    function link(scope, element, attrs) { 
 
     console.log(scope.idx); 
 
    } 
 
    return { 
 
     restrict: "A", 
 
     scope: { 
 
      idx: "=" 
 
     }, 
 
     link: link 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app="app" ng-controller="MainCtrl"> 
 
    <parent> 
 
    <div ng-repeat="index in indexes" idx="index.key"> 
 
     DIV - {{index.value}} 
 
    </div> 
 
    </parent> 
 
</div>

関連する問題