欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

AngularJs1.x自定义指令独立作用域的函数传入参数方法

程序员文章站 2022-06-20 08:38:20
在定义指令的scope属性如果设置成了{},那就成为了一个独立作用域,如果要传入一个方法,使用&,但是这里的传参有点不一样。 先看下官网解释: & or &attr...

在定义指令的scope属性如果设置成了{},那就成为了一个独立作用域,如果要传入一个方法,使用&,但是这里的传参有点不一样。

先看下官网解释:

& or &attr - provides a way to execute an expression in the context of the parent scope. if no attr name is specified then the attribute name is assumed to be the same as the local name. given and widget definition of scope: { localfn:'&myattr' }, then isolate scope property localfn will point to a function wrapper for the count = count + value expression. often it's desirable to pass data from the isolated scope via an expression and to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. for example, if the expression is increment(amount) then we can specify the amount value by calling the localfn as localfn({amount: 22}).

这里有个例子:

<!doctype html>
<html>
<head lang="en">
 <meta charset="utf-8">
 <title></title>
</head>
<body ng-app="app1">
<div ng-controller="myctrl">
 <div ng-repeat="item in items" my-component isolated-expression-foo="updateitem(item,temp)">
 {{item|json}}
 </div>
</div>
</body>
<script src="../scripts/angular.js"></script>
<script>
 var mymodule = angular.module('app1', [])
 .directive('mycomponent', function () {
 return {
 restrict:'a',
 scope:{
 isolatedexpressionfoo:'&'
 },
 link:function(scope,element,attr) {
 scope.isolatedexpressionfoo();
 }
 };
 })
 .controller('myctrl', ['$scope', function ($scope) {
 $scope.items=[{id:1,value:"test"},{id:2,value:"test2"}];
 $scope.updateitem = function (item,temp) {
 console.log("item param "+item.id);
 console.log("temp param " + temp);
 }
 }]);

</script>
</html>

以上这篇angularjs1.x自定义指令独立作用域的函数传入参数方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。