将值从指令传递给控制器 [英] Passing values from directive to controller

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

问题描述

下面是我的html模板:

Below is my html template:

<div ng-app="dr" ng-controller="testCtrl">
    <test color1="color1" data-method="ctrlFn(msg)"></test>    
</div>

以下是我的代码:

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

app.controller("testCtrl", function($scope) {
    $scope.ctrlFn = function(arg) {        
        alert(arg);
    }

});
app.directive('test', function() {
    return {
        restrict: 'E',
        scope: {
            fromDirectiveFn: '&method'
        },
        link: function(scope, elm, attrs) {
            //Way One
            scope.hello = "some message";
            scope.fromDirectiveFn(scope.hello);
        }
    }
});

<div ng-app="dr" ng-controller="testCtrl">
    <test color1="color1" data-method="ctrlFn(msg)"></test>    
</div>

为什么我会未定义而非某些人消息

以下是小提琴
http: //jsfiddle.net/j2K7N/27/

推荐答案

您的代码几乎是正确的,但是您有几个问题这里:

Your code is almost correct, however you had several issues here:

<test color1="color1" data-method="ctrlFn(msg)"></test>

在这里传递 ctrlFn()函数来自您的控制器,它带有一个未定义的参数 msg ,这会导致警报消息带有未定义文本。我建议将HTML代码修改为:

Here you pass the ctrlFn() function from your controller, which takes one undefined argument msg, that causes the alert message with "undefined" text. I suggest to modify the HTML code to this:

<test color1="color1" data-method="ctrlFn"></test>  

请注意,我将 ctrlFn 作为变量,而不是函数。

Note that I pass the ctrlFn as a variable, not function.

在你的指令代码中,我将范围绑定更改为 = 以确保 ctrlFn 将指向您的控制器功能。这也在指令的作用域和控制器(父)作用域之间建立了双向绑定。然后该指令的整个JS代码将如下所示:

In your directive code, I changed the scope binding to = to make sure that the ctrlFn will point to your controller function. This also sets up a two-way binding between the directive's scope and the controller (parent) scope. Then the whole JS code of the directive will look like this:

app.directive('test', function() {
    return {
        restrict: 'E',
        scope: {
            fromDirectiveFn: '=method'
        },
        link: function(scope, elm, attrs) {
            //Way One
            scope.hello = "some message";
            scope.fromDirectiveFn(scope.hello);
        }
    }
});

只需将& 替换为 = 。工作分叉: http://jsfiddle.net/L8masomq/

Just replacing the & to =. Working fork: http://jsfiddle.net/L8masomq/

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

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