2017-02-13 91 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>

相关问题