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

use*_*408 46 javascript html5 scope controller angularjs

看看这个小提琴,我需要改变什么,模板中的表达式使用我在HTML中定义的参数进行评估?SAVE按钮应该调用blabla()控制器的-function,因为我通过它?

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();
        };
      }
    }
});
Run Code Online (Sandbox Code Playgroud)

我真的没有看透.感谢帮助!

jai*_*ime 46

你可以property: '='像罗伊建议的那样设置双向数据绑定.因此,如果你想要两者keyvalue绑定到本地范围,你会这样做

scope: {
    key: '=',
    value: '='
},
Run Code Online (Sandbox Code Playgroud)

由于您传递了这些值,因此您可以在指令的控制器中访问它们.但是如果你想在父范​​围的上下文中运行一个函数,这似乎是你想要对accept属性做的事情,那么你需要告诉像这样的角度

scope: {
    accept: "&"
}
Run Code Online (Sandbox Code Playgroud)

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

controller: function($scope, $element, $attrs, $location) {
    $scope.save= function() {      
        $scope.accept()
    };
}
Run Code Online (Sandbox Code Playgroud)

这是一个jsfiddle


小智 15

scope: {
    accept: "&"
}
Run Code Online (Sandbox Code Playgroud)

使用小写字母表示函数名称,否则它不起作用.

  • 你不需要使用小写字母,只要知道如果你像'acceptSomething'那样写它就会在标记中将它称为'accept-something' (8认同)