AngularJS:如何传递参数/功能指令? [英] AngularJS: How to pass arguments/functions to a directive?

查看:359
本文介绍了AngularJS:如何传递参数/功能指令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个小提琴的,我有什么改变,在模板中的前pressions开始使用评估我的论点在HTML定义?保存按钮应调用控制器的布拉布拉()功能全,因为我通过它?

Look at this Fiddle, what do I have to change, that the expressions in the template get evaluated using the arguments I defined in the HTML? The SAVE-button should call the blabla()-function of the controller, since I pass it?

var myApp = angular.module('MyApp',[])
myApp.directive('editkeyvalue', function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            accept: "expression"
        },
        template : '<div><label class="control-label">{{key}}</label>' +
        '<label class="control-label">{{key}}</label>' +
          '<input type="text" ng-model="value" />'+
        '<button type="button" x-ng-click="cancel()">CANCEL</button>' +
        '<button type="submit" x-ng-click="save()">SAVE</button></div>',

      controller: function($scope, $element, $attrs, $location) {
        $scope.save= function() {
          $scope.accept();
        };
      }
    }
});

我真的不通过看到的。感谢您的帮助!

I do not really see through that. Thanks for help!

推荐答案

您可以设置双向数据与绑定属性:'='罗伊建议。所以,如果你想同时绑定到本地范围,你会做

You can set two way data binding with property: '=' as Roy suggests. So if you want both key and value bound to the local scope you would do

scope: {
    key: '=',
    value: '='
},

由于您传递这些价值,你有你的指令的控制器访问它们。但如果你想运行在父范围,这似乎是要与接受属性做什么的情况下的函数,那么你就需要告诉角像这样

Since you are passing these values, you have access to them in your directive's controller. But in case you want to run a function in the context of the parent scope, which seems to be what you want to do with the accept attribute, then you would need to tell angular like this

scope: {
    accept: "&"
}

现在,从你的保存方法,你可以通过调用传递的函数接受

Now, from your save method you could call the function passed via accept

controller: function($scope, $element, $attrs, $location) {
    $scope.save= function() {      
        $scope.accept()
    };
}

下面是一个的jsfiddle

这篇关于AngularJS:如何传递参数/功能指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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