Angular directive test with $parse
Use $parse to change value with directive
by taly2808
HTML
<script src="https://code.angularjs.org/1.3.2/angular.js"></script>
<div ng-controller="myCtrl">
<h3>Title</h3>
<br/>
<input ng-model="inputdata.title">
<h3>Isolated scope</h3>
<div>
<button ng-update1="inputdata.title">click to set title to Button 1 (works with $parse)</button>
<button ng-update2="inputdata.title">click to set title to Button 2</button>
</div>
<small>Whenever a directive does not use an isolate scope and you specify a scope property using an attribute, and you want to modify the value, use $parse.</small>
</div>
CSS
.selected {
background-color: #ff0000;
}
JavaScript
var app = angular.module('myApp', []);
app.directive('ngUpdate1', function ($parse) {
return function (scope, element, attrs) {
var model = $parse(attrs.ngUpdate1);
console.log(model(scope)); // logs "test"
element.bind('click', function () {
model.assign(scope, "Button 1");
scope.$apply();
});
};
});
app.directive('ngUpdate2', function () {
return function (scope, element, attrs) {
element.bind('click', function () {
scope.$apply(function () {
scope.inputdata.title = "Button 2";
});
});
};
});
app.controller('myCtrl', function ($scope) {
$scope.inputdata = {
title: "test"
};
});