[英]problems with the scope variable over communication between the directives in angularjs
I am doing scripting using angularjs.I have created an app and included some selfdefined directives into it.I am getting problem when one of my directives is communicating with the other one and I am not able to access the scope variables in one directive from the other.I am often confused with the usage of this and $scope in angularjs.Help me out on this 我正在使用angularjs进行脚本编写。我已经创建了一个应用程序并在其中包含一些自定义指令。当我的一个指令与另一个指令通信时,我遇到了问题,并且无法从一个指令访问作用域变量other。我经常对angularjs中this和$ scope的用法感到困惑。
Here is my html file, 这是我的html文件,
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
<script type="text/javascript" src="../Js/angular.js"></script>
<script type="text/javascript" src="../Js/directiveScript.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="directiveController">
<userdirective secondary></userdirective>
</div>
</body>
</html>
and this is the javascript file im working on 这是我正在处理的javascript文件
var directiveApp = angular.module("myApp", []);
directiveApp.controller("directiveController", function($scope) {
});
directiveApp.directive("userdirective", function() {
return {
restrict : "E",
controller : function($scope) {
$scope.message = "hi";
},
link : function() {
alert("from userdefined element");
}
};
});
directiveApp.directive("secondary", function() {
return {
require : "userdirective",
link : function(scope, element, attrs, userdirectivectrl) {
alert(userdirectivectrl.message);
}
};
});
When Iam doing this,the directive named secondary is giving an alert with undefined instead of showing original value.If I change the declaration of variable in the controller of the first directive to this.message ,it works fine.why is it so? Iam执行此操作时,名为secondary的指令会给出未定义的警报,而不是显示原始值。如果我将第一个指令的控制器中的变量声明更改为this.message ,它可以正常工作。为什么呢?
Try 尝试
alert(scope.message);
instead of 代替
alert(userdirectivectrl.message);
The message is defined on scope not controller. 该消息是在作用域而非控制器上定义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.