ng-单击角度指令 - 从根范围传递函数

ng-click in angular directive - pass function from root scope

本文关键字:范围 传递函数 指令 单击 ng-      更新时间:2023-09-26

修复了这个问题,这是显示它工作的最后一个小提琴:

http://jsfiddle.net/mbaranski/tfLeexdc/

我有一个指令:

var StepFormDirective = function ($timeout, $sce, dataFactory, $rootScope) {
    return {
        replace: false,
        restrict: 'AE',
        scope: {
            context: "=",
            title: "="
        },
        template: '<h3>{{title}}</h3><form id="actionForm" class="step-form"></form><button ng-click="alert()" type="button">Save</button>',
        link: function (scope, elem, attrs) {
        }
    }
}

如何让alert()从控制器执行某些操作?

这是一个小提琴:http://jsfiddle.net/mbaranski/tfLeexdc/

Angular 可能会抽搐,所以我构建了一个全新的小提琴来演示完成这项工作所需的所有"胶合"部分。

首先,您没有将属性传递给指令,因此我进行了调整:

// You have to pass the function in as an attribute
<hello-directive list="osList" func="myFunc()"></hello-directive>

其次,您在模板中使用onclick而不是ng-click,这是问题的一部分,所以我进行了切换:

// You need to use "ng-click" instead of "onclick"
template: '<h3>{{list}}</h3><button ng-click="func()" type="button">Button</button>',

最后,您需要在指令范围内绑定函数,然后通过绑定名称调用它:

scope: {
  list: "=",
  // Bind the function as a function to the attribute from the directive
  func: "&"
},

这是一个工作小提琴

所有这些粘在一起看起来像这样:

.HTML

<div ng-controller="MyCtrl">
  Hello, {{name}}!
  <hello-directive list="osList" func="myFunc()"></hello-directive>
</div>

爪哇语

var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
  $scope.name = 'Angular Directive';
  $scope.osList = "Original value";
  $scope.stuffFromController = {};
  $scope.myFunc  = function(){ alert("Function in controller");};
};
var HelloDirective = function() {
  return {
    scope: {
      list: "=",
      func: "&"
    }, // use a new isolated scope
    restrict: 'AE',
    replace: false,
    template: '<h3>{{list}}</h3><button ng-click="func()" type="button">Button</button>',
    link: function(scope, elem, attrs) {
      }
  };
};
myApp.directive("helloDirective", HelloDirective);

如果要执行在其他地方定义的函数,请确保通过 scope 指令属性传入该函数。

在这里你可以做:

scope: {
  context: '=', 
  title: '=',
  alert='&' // '&' is for functions
}

在使用指令的位置,您将传递函数的"表达式"(不仅意味着函数,还意味着您希望在单击发生时发生函数的实际调用。

<step-form-directive alert="alert()" title=".." context=".."></step-form-directive>