2014-09-03 18 views
-1

我有一個向控制器提供數據的工廠,但是當我通過指令調用數據時不會綁定數據。如何從外部控制器將數據導入指令模板?

myApp.directive('user',function(){ 
    return{ 
     replace:true, 
     restrict:'E', 
     scope:{ 
     }, 
     template:'<h1>User name: {{userName}}</h1>', 
     link: function(scope,elem,attr){ 
     } 
    } 
}); 

myApp.controller('MembriController', ['$scope', 'facebook',function($scope,facebook){ 
    facebook.membersData().then(function(response){ 
     //console.log(response); 

     var obj = angular.fromJson(response); 
     var nrMembri = obj.data.length; 
     $scope.nrMembri=nrMembri; 
     $scope.users=obj.data; 
     for(var i=0; i<nrMembri; i++){ 
      var userName = obj.data[i].name; 
      $scope.userName=userName; 
     }; 
    }); 
}]); 

<div id="membri"> 
<h1>Hera are all of {{nrMembri}} members</h1> 

<div ng-repeat="user in users | orderBy:'name'"> 
    <user userName="userName"></user> 
</div> 

http://plnkr.co/edit/whAnVxy18NfhM4MtqVCl?p=catalogue

+0

可能重複http://stackoverflow.com/questions/ 25370582 /共享數據之間-A-指令和 - 一個控制器功能於不同模塊) – Fedaykin 2014-09-03 14:54:05

回答

0

我建議你使用一個服務/工廠和注射它兩邊總是分享你的控制器和指令之間的數據。

app.factory('SharedService', function() { 
    return { 
    sharedObject: { 
     value: '', 
     value2: '' 
    } 
    }; 
}); 

app.controller('FirstCtrl', function($scope, SharedService) { 
    $scope.model = SharedService.sharedObject; 
}); 

app.directive('myDirective',['SharedService', function(SharedService){ 
    return{ 
    restrict: 'E', 
    link: function(scope){ 
     scope.model = SharedService.sharedObject; 
    }, 
    template: '<div><input type="text" ng-model="model.value"/></div>' 
    } 
}]); 

下面是一個plunkr示出如何可以實現: http://plnkr.co/edit/Q1VdKJP2tpvqqJL1LF6m

([一條指令和在不同的模塊控制器之間共享數據]的