Skip to content

Instantly share code, notes, and snippets.

@KiT106
Created October 21, 2016 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KiT106/c241348723df86b7216a7e6faef7c53e to your computer and use it in GitHub Desktop.
Save KiT106/c241348723df86b7216a7e6faef7c53e to your computer and use it in GitHub Desktop.
AngularJS : 2 controllers inside a scope
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Egghead Videos</title>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/foundation/6.2.4/foundation.css">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</head>
<body ng-app="app" scope="{{$id}}">
<!-- ng-controller create new scope -->
<div ng-controller="Foo as foo" scope="{{$id}}">
<p ng-click="foo.fooClick()" value="{{model.message}}">Hello world</p>
<abc scope="{{$id}}" value="{{model.message}}"></abc>
</div>
</body>
</html>
var app = angular.module("app", []);
app.controller("Foo", function Foo($scope, $log) {
var vm = this;
$scope.model = {
message: "Foo controller"
};
vm.fooClick = function () {
$log.info($scope);
$log.info(vm);
}
});
app.controller("Bar", function Bar($scope, $log) {
var vm = this;
$scope.model = {
message: "Bar controller"
};
vm.barClick = function () {
$log.info($scope);
$log.info(vm);
}
});
app.directive("abc", function () {
return {
// scope = false to prevent directive create a new scope
// So scope is in ng-controller
scope: false,
controller: "Bar as bar",
template: '<div scope="{{$id}}">\n' +
' <div ng-click="bar.barClick()">Inside ABC</div>\n' +
' <small>{{model.message}}</small>\n' +
'</div>',
link: function (scope, element) {
// Override model define in Foo n' Bar controllers
scope.model = {
message: "abc directive"
};
}
};
});
@KiT106
Copy link
Author

KiT106 commented Oct 21, 2016

What if 2 controller as the same alias?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment