Angularjs-函数在子范围中未定义,即使它在父范围中
我有这样的想法: 在这个plunkr中,我调用了一个指令,该指令使用“&”操作符从父作用域获取函数“test”。 为什么当我尝试使用该函数时,它返回“undefined” HTML:Angularjs-函数在子范围中未定义,即使它在父范围中,angularjs,angularjs-directive,angularjs-scope,Angularjs,Angularjs Directive,Angularjs Scope,我有这样的想法: 在这个plunkr中,我调用了一个指令,该指令使用“&”操作符从父作用域获取函数“test”。 为什么当我尝试使用该函数时,它返回“undefined” HTML: <!DOCTYPE html> <html ng-app="plunker"> <head> <meta charset="utf-8" /> <title>AngularJS Plunker</title> &l
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p my-directive>Hello {{name}}!</p>
</body>
</html>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.test = function test(){
alert('y');
}
console.log(angular.noop);
console.log($scope.test);
});
app.directive('myDirective', [
function () {
return {
restrict: 'EAC',
scope: {
value: '@', // some value
test: '&' // the function
},
link: function(scope, element, attrs) {
function functionName(func) {
var ret = func.toString();
ret = ret.substr('function '.length);
ret = ret.substr(0, ret.indexOf('('));
return ret;
}
console.log(scope.test());
}
};
}
]);
使用隔离作用域时,在声明指令时,通过属性定义父作用域和指令作用域之间的链接 所以,这个代码:
scope: {
value: '@', // some value
test: '&' // the function
},
表示“在声明指令的元素上查找名为value
和test
的属性。”
因此,它期望:
<body ng-controller="MainCtrl">
<p my-directive value="{{value}}" test="test()">Hello {{name}}!</p>
</body>
Hello{{{name}
有关文档,请参阅本手册的“隔离指令的范围”一节。Davin完全正确 当您使用remove the scope(删除指令中定义的范围)时,这将与您预期的完全一样(弹出警报) 这是你的plunker叉子:很好用 默认情况下,指令的范围从其所在的控制器继承;但是通过在指令上定义scope属性,您已经创建了一个不从控制器继承的“隔离范围”