Skip to content

Instantly share code, notes, and snippets.

@groner
Created January 31, 2011 19:17
Show Gist options
  • Save groner/804613 to your computer and use it in GitHub Desktop.
Save groner/804613 to your computer and use it in GitHub Desktop.
angular x:local scope widget
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ng="http://angularjs.org/">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>x:local example</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="http://code.angularjs.org/0.9.10/angular-0.9.10.min.js" ng:autobind="autobind"></script>
<script src="angular.local.js" type="text/javascript"></script>
</head>
<body ng:init="item = { name: 'Bozo', color: 'blue', feathers: false }">
<button ng:click="item = { name: 'Bozo', color: 'blue', feathers: false }">Bozo</button>
<button ng:click="item = { name: 'ozoB', color: 'yellow', feathers: true }">ozoB</button>
<h2>with x:local="item"</h2>
<fieldset x:local="item">
<legend>item</legend>
<ul>
<li>$id: {{ $id }}</li>
<li>name: <input name="name"></li>
<li>color: <input name="color"></li>
<li>feathers: <input type="checkbox" name="feathers"></li>
</ul>
</fieldset>
<h2>regular</h2>
<ul>
<li>item.$id: {{ item.$id }}</li>
<li>item.name: <input name="item.name"></li>
<li>item.color: <input name="item.color"></li>
<li>item.feathers: <input type="checkbox" name="item.feathers"></li>
</ul>
</body>
</html>
// Creates a local scope using the specified expression
angular.widget('@x:local', function(expression, element) {
element.removeAttr('x:local');
element.replaceWith(this.comment('x:local: ' + expression));
var template = this.compile(element);
return function(linkElement) {
var currentScope = this;
var childScope = template(element, angular.scope(currentScope));
this.$onEval(function() {
var value = currentScope.$get(expression);
if (value !== childScope) {
angular.extend(childScope, value);
currentScope.$set(expression, childScope);
}
});
linkElement.after(childScope.$element);
currentScope.$onEval(childScope.$eval);
childScope.$init();
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment