bind model without scope
Bind a model from an attirbute without explicit scope. using $parse.
HTML
<script src="http://code.angularjs.org/1.1.3/angular.js"></script>
<script src="http://fonts.googleapis.com/css?family=Droid+Sans:400,700"></script>
<h3>Attribute bind demo</h3>
<div ng-controller="DemoCtrl">
scope: {{ data.email }} <button ng-click="reset()">reset</button>
<br><br>
<div data-my-directive="data.email" ng-click="changeValue('[email protected]')">Click me to change the email </div>
<br><br>
Click the directive to change the scope value
</div>
CSS
* {
font-family: 'Droid Sans', sans-serif;
}
#log {
margin-top:10px;
font-size:10px
}
JavaScript
var app = angular.module('demo', []);
app.controller('DemoCtrl', function($scope) {
$scope.reset = function() {
$scope.data = {
email: '[email protected]'
};
};
$scope.reset();
});
app.directive('myDirective', ['$parse', function($parse) {
return {
restrict: 'A',
scope: true,
link: function(scope, iElement, iAttrs) {
var attrModel = $parse(iAttrs.myDirective)
function updateContents() {
// get value from the attribute and update directive contents
iElement.html('directive: ' + attrModel(scope));
}
scope.$watch(attrModel, function(newValue) {
// watch the attribute model
updateContents();
});
scope.changeValue = function(newValue) {
alert("scope:"+JSON.stringify(iAttrs));
// assign value to the attribute model
attrModel.assign(scope, "hello");
updateContents();
}
updateContents();
}
}
}]);