AngularJS - $parse and $observe examples
HTML
<div ng-app="myApp">
<div ng-controller="MyCtrl">
vm.checked: <span ng-bind="vm.checked"></span>
<br>
<br> vm.text: <span ng-bind="vm.text"></span>
<br>
<br> vm.text2: <span ng-bind="vm.text2"></span>
<br>
<br>Click me to toggle:
<input type="checkbox" ng-model="vm.checked">
<br/>
<input type="text" value="" clear-and-disable="{{vm.checked}}" ng-model="vm.text" />
<input type="text" value="" clear-and-disable2="vm.checked" ng-model="vm.text2" />
</div>
</div>
CSS
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script> <style>
JavaScript
//Include angular-ui dependency in resources on the side and as 'ui'
angular.module('myApp', [])
.controller("MyCtrl", function ($scope) {
$scope.vm = {
checked: false,
text: "test",
text2: "Hi!"
};
})
.directive('clearAndDisable', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
attrs.$observe('clearAndDisable', function (modelValue) {
if (modelValue === 'true') {
ngModel.$setViewValue("");
element.prop('disabled', true);
} else {
element.prop('disabled', false);
}
ngModel.$render();
});
}
};
})
.directive('clearAndDisable2', function ($parse) {
return {
link: function (scope, element, attrs) {
var updateContents = function (enable) {
if (enable == true) {
element.prop('disabled', true);
} else {
element.prop('disabled', false);
}
}
var attrModel = $parse(attrs.clearAndDisable2);
var model = $parse(attrs.ngModel);
debugger;
scope.$watch(attrModel, function(newValue) {
if(newValue == true){
model.assign(scope, "bil");
}
//updateContents(newValue);
});
}
};
})