var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', MyCtrl);
myApp.service('efficientWatch', efficientWatch);
MyCtrl.$inject = ['efficientWatch'];
function MyCtrl(efficientWatch) {
var self = this;
efficientWatch.watch('reactionText', self, function (newval) {
if (newval == 'watched') {
self.reacted = true;
}else{
self.reacted = false;
};
});
self.reacted = false;
self.placeholder = 'type the watched word';
}
function efficientWatch() {
this.watch = function (name, controllerProto, func) {
Object.defineProperty(controllerProto,
name, {
get: function () {
return this._personName;
},
set: function (newValue) {
this._personName = newValue;
//Call method on update
if (typeof func == 'function') func(newValue);
},
enumerable: true,
configurable: true
});
};
};
<div ng-controller="MyCtrl as vm">Type a text here:
<input type="text" ng-model="vm.reactionText" placeholder="{{vm.placeholder}}" />
<div ng-class="{'boxReacted': vm.reacted, 'boxNotReacted': !vm.reacted}" class="format box"></div>
<div class="format">vm.reacted is: {{vm.reacted}}</div>
</div>
.format {
margin-top: 20px;
width: 50%;
min-height: 50px;
}
.box {
border: 1px solid #ccc;
}
.boxReacted {
background-color: yellow;
}
.boxNotReacted {
background-color: green;
}
External resources loaded into this fiddle: