AngularJS - 将变量传递到作用域(从指令到在控制器中使用它)不起作用 [英] AngularJS - passing variable to scope (from directive to use it in controller) not working

查看:27
本文介绍了AngularJS - 将变量传递到作用域(从指令到在控制器中使用它)不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would ask for some help and explanation on the given issue. It seems like I can not pass variable to scope from directive to use it in controller, variable is called caret_position. Please see below code.

控制器

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); // stackoverflow.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; // stackoverflow.com note: this is not working
                scope.$apply(); // stackoverflow.com note: not working as well
                console.log('my current position: ' + caret_position);
            });
        }
    }
});

推荐答案

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

The recommended way to share data between directives and controllers is by using a Service, you can create one by using the factory method:

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

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

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

And then you may inject your SharedService on both your directive and controller.

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

Here is a more detailed example about sharing data between controllers and directives:

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

希望有帮助

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

Update: I just edited your example to use that concept and it is working, take a look: http://plnkr.co/edit/2pUODHCd9qTRcQTiziC2?p=preview

这篇关于AngularJS - 将变量传递到作用域(从指令到在控制器中使用它)不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆