简体   繁体   中英

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

Here is my html file,

<?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

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?

Try

alert(scope.message);

instead of

alert(userdirectivectrl.message);

The message is defined on scope not controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM