AngularJS:将对象从指令传递到控制器 [英] AngularJS: Pass object from directive to controller

查看:43
本文介绍了AngularJS:将对象从指令传递到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的指令中,我正在实例化一个对象.

In my directive, I'm instantiating an object.

我想将此对象传递给与该指令关联的控制器的范围.我该怎么办?

I'd like to pass this object to the scope of the controller I associate with the directive. How do I do that?

请记住,这是一个孤立的代码,可让您理解该问题.在实际问题中,将无法在控制器内部实例化该对象.

Please keep in mind this is an isolated code for you to understand the issue. In the actual issue it won't help to instantiate that object inside of the controller.

我知道指令中的scope对象是用于传递HTML中指定的值的,我以这种方式编写它以帮助您了解我要执行的操作.

I know that the scope object in the directive is for passing values that are specified in the HTML, I wrote it that way to help you understand what I'm trying to do.

angular.module('test', [])

.controller('test', ['$scope', function($scope) {
    alert($scope.obj); //Needs to contain {value: 'bla'}

}])

.directive('pTest', ['$compile', function($compile) {
    var object = {value: 'bla'};

    return {
        scope: {
            obj: object //how can I do that?
        },
        controller: 'test'
    };
}]);

推荐答案

您可以在该方向的链接功能中执行此操作.由于要在范围上设置值,因此可以使用链接功能的scope参数.您还可以在控制器上设置对象,因为链接函数的第四个参数(可选)是指令的控制器.

You can do this in the link function of the direction. Since you want to set the value on the scope, you can use the scope parameter of the link function. You can also set the object on the controller, since The fourth argument (optional) argument to the link function is the controller for the directive.

.directive('pTest', ['$compile', function($compile) {
    var object = {value: 'bla'};

    return {
        controller: 'test',
        link: function(scope, elements, attrs, controller) {
           scope.obj = object;
           // or
           controller.obj = object;
        }

    };
}]);

现在假设您不想在指令的返回中使用作用域"成员来隔离作用域.从您的示例中,我认为您实际上并不需要隔离的范围.(无论如何,链接功能也可以在其中使用.)

Now that assume you don't want to isolate your scope by using a "scope" member in the return of your directive. From your example I don't think you actually want an isolated scope. (Regardless, the link function would work there too.)

这篇关于AngularJS:将对象从指令传递到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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