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

标签 javascript html controller scope angularjs

this Fiddle ,我必须更改什么,使用我在 HTML 中定义的参数评估模板中的表达式?保存按钮应该调用 Controller 的 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();
        };
      }
    }
});

我真的看不透。感谢您的帮助!

最佳答案

您可以按照 Roy 的建议使用 property: '=' 设置两种方式的数据绑定(bind)。因此,如果您希望将 keyvalue 都绑定(bind)到本地范围,您可以这样做

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

由于您正在传递这些值,因此您可以在指令的 Controller 中访问它们。但是如果你想在父范​​围的上下文中运行一个函数,这似乎是你想用 accept 属性做的,那么你需要像这样告诉 angular

scope: {
    accept: "&"
}

现在,您可以从您的save 方法调用通过accept

传递的函数
controller: function($scope, $element, $attrs, $location) {
    $scope.save= function() {      
        $scope.accept()
    };
}

这是一个 jsfiddle

关于javascript - AngularJS:如何将参数/函数传递给指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13725938/

相关文章:

javascript - JS 从对象数组中过滤某些部分

javascript - React-redux 状态和 Prop 已更新但组件未重新渲染

spring - 如何将 detectorHandlerMethodsInAncestorContexts 设置为 true?

java - 无法在 spring 中填充 modelAttribute

javascript - 如何在 Meteor 中切换文本中随机句子的颜色

javascript - 由于客户端未注册,在服务 worker 的第一次页面加载中未执行获取事件

javascript - 如何获取输入字段中的javascript函数参数值

javascript - 使用 Express 和 Node.js 的谷歌地图 API

css - Div重叠问题

javascript - 从组件中的 Action 调用 Controller Action