我已经使用$ watch在angular JS中实现了notify属性更改事件。无论什么时候更改模型,我都会得到newvalue
函数中的旧值和$watch
。但问题是当我加载数据初始时,我已将employee.firstname
属性绑定到名为oldvalue
的新属性。当我更改控件的值时,oldvalue也会发生变化。如何限制更改oldvalue
属性的初始值。
angular.module('app', []);
angular.module('app').controller('ctrl', function ($scope) {
$scope.size = 100;
var employee = {
"employees": [
{ "firstName": "John", "lastName": "Doe" },
{ "firstName": "Anna", "lastName": "Smith" },
{ "firstName": "Peter", "lastName": "Jones" }
]
};
$scope.employees = employee;
});
angular.module('app').directive('notifypropertychanged', function () {
return {
link: function (scope, el, attrs) {
scope.$watch(attrs['notifypropertychanged'], function (newVal, oldVal) {
var entity = attrs['entity'];
el.css('height', newVal + 'px');
});
}
}
});
<body ng-controller="ctrl">
<input ng-repeat="emp in employees.employees"
oldvalue="{{emp.firstName}}" entity="entity{{$index}}"
ng-model="emp.firstName" notifypropertychanged="emp.firstName" />
</body>