AngularJS - 将变量传递到范围(从指令在控制器中使用它)不起作用

AngularJS - passing variable to scope (from directive to use it in controller) not working

我会就给定的问题寻求一些帮助和解释。似乎我无法将变量从指令传递到范围以在控制器中使用它,变量称为 caret_position。请看下面的代码。

控制器

var myApp = angular.module('myApp', []);

myApp.controller('Composer', function Composer($scope, $http) {

    // getting snippets json data
    $http.get('data/snippets/default.json').success(function(data) {
        $scope.snippets = data;
        $scope.snippets.count = data.length;
    });

    // adding snippet to composed text
    $scope.composed_text = '';
    $scope.snippet_insert = function() {
        var snippet = this.item.content;

        console.log($scope.caret_position); // whosebug.com note: this is not working
    };
});

指令:

myApp.directive('caretPosition', function() {
    return {
        link: function(scope, element, attrs) {
            element.bind('keyup click', function(e){
                var caret_position = element[0].selectionStart;
                scope.caret_position = caret_position; // whosebug.com note: this is not working
                scope.$apply(); // whosebug.com note: not working as well
                console.log('my current position: ' + caret_position);
            });
        }
    }
});

您需要在具有隔离范围的指令上使用 2 路绑定变量。这就是指令能够更新封闭 controller.you 的范围 属性 的方式,可以通过在指令定义对象上指定 scope:{catet属性:'='}

在指令和控制器之间共享数据的推荐方法是使用服务,您可以使用 factory 方法创建服务:

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

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

然后你可以在你的指令和控制器上注入你的SharedService

这里有一个关于在控制器和指令之间共享数据的更详细的例子:

http://plnkr.co/edit/Q1VdKJP2tpvqqJL1LF6m?p=preview

希望对您有所帮助

更新: 我刚刚编辑了您的示例以使用该概念并且它正在运行,请看一下: http://plnkr.co/edit/2pUODHCd9qTRcQTiziC2?p=preview

make the service in
var myApp = angular.module('mean.mapping2');
myApp.factory('SharedService', function() {
    return {
        caretInfo: {
            position: 0
        }
    };
});

inject service in controller
angular.module('mean.mapping2').controller('mapProperties', ['$scope', 'Global', 'Mapping2', '$http', '$stateParams','SharedService',

console.log( $scope.caret = SharedService.caretInfo);//controller part for calling services

in directive use as 
 .directive('repeatEvents', function ($timeout,SharedService) {

 .directive('setupConnections', function ($location,SharedService) {//i have two directive


use this in directive
 var caret_position = items;
                            SharedService.position = caret_position;
                            console.log('Caret current position: ' + SharedService.position);