This example demonstrate the code sample for communication between non-nested directives. The templates used for different directives make use of bootstrap CSS classes for creating decent UI fields.
Instruction: Type your name in the text field below:

Notes

  • hello directive such as <hello name="Calvin Hobbes"></hello>. This directive does following:
    • Print the message "Hello {\{name}}! How are you doing today?
    • Display the input field and bind the field with "name" property
  • bye directive such as <bye></bye>. This directive prints "Bye {\{name}}!".
  • hello and bye directives are not used within each other. Pay attention to the code below
  • Service is used to communicate between two directives take a look at the code below.

The code below demonstrates the fact that hello and bye directives are non-nested.

			
<hello name="Calvin Hobbes"></hello>
<bye></bye>

The code below demonstrates following:

			
angular.module('HelloModule', [])
.directive( 'hello', function( helloservice) {
return {
restrict: "E",
scope:{
name: '@'
},
controller: function( $scope, helloservice ) {
$scope.updateName = function() {
helloservice.setName( $scope.name );
};
},
link: function( scope, element, attrs ) {
helloservice.setName( scope.name );
},
templateUrl: '/assets/templates/hello1.html'
}
})
.directive( 'bye', function( helloservice ) {
return {
restrict: "E",
scope:{
},
controller: function( $scope, helloservice ) {
$scope.name = helloservice.getName();
},
link: function( scope, element, attrs ) {
scope.$watch(function() {
return helloservice.name;
}, function() {
scope.name = helloservice.name;
});
},
templateUrl: '/assets/templates/bye.html'
}
})
.factory('helloservice', function(){
return new User();
});

function User() {
this.name = '';

this.setName = function( name ) {
this.name = name;
};

this.getName = function() {
return this.name;
};
}
comments powered by Disqus