将数据从控制器发送到指令

Send data from controller to directive

我想将其发送到我的指令,但我希望该数据在控制器中的数据发生变化时保持更新。

// 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;
}

这就是我使用指令的方式。问题是它总是 returns 名字而不是控制器更改后的新名字。

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

谢谢。

Without using as in controller, you cannot use controller.prop inside the scope.

Inside the controlleryou need to call the method using its $scope or this.

  • 检查下面的代码。

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>

试试这个,你只需将 $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>