简体   繁体   English

AngularJS:如何将参数/函数传递给指令?

[英]AngularJS: How to pass arguments/functions to a directive?

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? 看看这个小提琴 ,我需要改变什么,模板中的表达式使用我在HTML中定义的参数进行评估? The SAVE-button should call the blabla() -function of the controller, since I pass it? SAVE按钮应该调用控制器的blabla()函数,因为我通过它?

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. 您可以使用property: '='设置双向数据绑定property: '='正如Roy建议的那样。 So if you want both key and value bound to the local scope you would do 因此,如果您希望keyvalue绑定到本地范围,那么您可以这样做

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 但是如果你想在父作用域的上下文中运行一个函数,这似乎是你想用accept属性做的,那么你需要告诉像这样的角度

scope: {
    accept: "&"
}

Now, from your save method you could call the function passed via accept 现在,您可以通过save方法调用通过accept传递的函数

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

Here's a jsfiddle 这是一个jsfiddle

scope: {
    accept: "&"
}

Use lowercase letters for function names, otherwise it doesn't work. 使用小写字母表示函数名称,否则它不起作用。

Just a quick note that you dont need the wrapping function save. 只需快速说明您不需要包装功能保存。 Just call this in the template: 只需在模板中调用它:

'<button type="submit" x-ng-click="accept()">SAVE</button></div>',

That transposes the function call and passes the parameters as expected. 转换函数调用并按预期传递参数。

This simplifies code and makes it a lot easier to read. 这简化了代码并使其更易于阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM