Created
October 21, 2016 10:43
-
-
Save KiT106/c241348723df86b7216a7e6faef7c53e to your computer and use it in GitHub Desktop.
AngularJS : 2 controllers inside a scope
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | |
}; | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What if 2 controller
as
the same alias?