Angularjs Dynamic Controllers inside directive
by bullrout
HTML
<script src="https://code.angularjs.org/1.3.0/angular.min.js"></script>
<communicator controller-name="MainCtrl" ></communicator>
JavaScript
var app = angular.module('myApp',['controllerTest']).
directive('communicator', function(){
return {
restrict : 'E',
scope:{},
template:"<input type='text' ng-model='message'/><input type='button' value='Send Message' ng-click='sendMsg()'><br/>",
controller : "@",
name:"controllerName"
}
});
(function (module) {
module.controller('MainCtrl', ['$scope', '$rootScope', '$window', 'SimpleService',
function ($scope, $rootScope, $window, SimpleService) {
$scope.sendMsg = function(){
// alert( $scope.message + " : sending message via MainCtrl");
//console.log(SimpleService);
alert(SimpleService.getStuff());
}
}
]);
}(angular.module('controllerTest',['testFactorie'])));
(function (module) {
/* return a mock json file
* */
module.factory("SimpleService", ["$http", "$q", function($http, $q){
return {
getStuff: function() {
var deferred = $q.defer();
$http.get("google.com")
.success(function(data) {
deferred.resolve(data);
}).error(function(msg, code) {
deferred.reject(msg);
});
return deferred.promise;
}
};
}]);
}(angular.module('testFactorie', ['controllerTest'])));
/*
controller("PhoneCtrl",function($scope){
$scope.sendMsg = function(){
alert( $scope.message + " : sending message via Phone Ctrl");
}
}).
controller("LandlineCtrl",function($scope){
$scope.sendMsg = function(){
alert( $scope.message + " : sending message via Land Line Ctrl ");
}
});
*/