2017-02-13 39 views
1

我想將它發送給我的指令,但如果控制器中的數據發生更改,我希望數據保持更新。將數據從控制器發送到指令

// Controller 
angular 
    .module('app') 
    .controller('IndexController', IndexController) 

IndexController.$inject = []; 
function IndexController() { 
    var vm = this; 
    vm.name = 'John'; 

    newName = function() { 
     vm.name = 'Brian'; 
    } 
    newName(); 

} 

// Directive 
angular 
    .module('app') 
    .directive('userName', userName); 

userName.$inject = ['$document']; 

function userName($document) { 

    var directive = { 
     restrict: 'EA', 
     template: '<div id="user"></div>', 
     replace: true, 
     scope: { 
      name: '=' 
     }, 

     link: function(scope, elem, attrs) { 
      console.log(scope.data); 
     } 
    } 
    return directive; 
} 

這是我如何使用該指令。問題是它總是返回控制器中更改後的名字而不是新名稱。

<div ng-controller="indexController"> 
    <user-name name="indexController.name"> 
</div> 

謝謝。

回答

1

試試這個,你只需要注入$scope到您的Indexcontroller

angular 
 
    .module('app', []) 
 
    .controller('IndexController', function($scope) { 
 
    var vm = this; 
 
    vm.name = 'John'; 
 

 
    vm.newName = function() { 
 
     vm.name = 'Brian'; 
 
     console.log(vm.name); 
 
    } 
 
    //vm.newName(); 
 

 
}) 
 
.directive('userName', ['$document', function() { 
 

 
    var directive = { 
 
     restrict: 'E', 
 
     template: '<div id="user"></div>', 
 
     replace: true, 
 
     scope: { 
 
      name: '=' 
 
     }, 
 

 
     link: function(scope, elem, attrs) { 
 
      console.log(scope.name); 
 
     } 
 
    } 
 
    return directive; 
 
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="app" ng-controller="IndexController as vm"> 
 

 
<user-name name="vm.name"></user-name> 
 
    <button ng-click="vm.newName()">Click</button> 
 
</div>

+0

謝謝。這工作完美。我想我還是很困惑$ scope,vm和這個 – handsome

+0

行..只有在給定的情況下才有效。但如果我有一個它不起作用。還有什麼遺漏?謝謝! – handsome

+0

你不需要改變任何東西。我只是更新上面的答案,與ng-click一起工作。 – nivas

0

在控制器中不使用as,您不能在範圍內使用controller.prop

控制器內部需要使用其$scopethis來調用該方法。

  • 檢查下面的代碼。

angular 
 
    .module('app', []) 
 
    .controller('IndexController', function($scope) { 
 
    
 
    $scope.name = 'John'; 
 

 
    $scope.newName = function() { 
 
     $scope.name = 'Brian'; 
 
    } 
 
    $scope.newName(); 
 

 
}) 
 
.directive('userName', ['$document', function() { 
 

 
    var directive = { 
 
     restrict: 'E', 
 
     template: '<div id="user"></div>', 
 
     replace: true, 
 
     scope: { 
 
      name: '=' 
 
     }, 
 

 
     link: function(scope, elem, attrs) { 
 
      console.log(scope.name); 
 
     } 
 
    } 
 
    return directive; 
 
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="app" ng-controller="IndexController"> 
 

 
<user-name name="name"></user-name> 
 
</div>

相關問題