我無法讓getterSetter在ng-model指令中工作。 請看看這個plunker:http://plnkr.co/edit/Tx0nyvvbuKqf1ZpsRTPu?p=preview如何在具有隔離範圍的角度指令中使用getterSetter?
如果您使用未註釋的模板,該示例的行爲就好像它不知道getSet()是它應該調用的函數。
如果您取消註釋其他模板(並註釋掉第一個模板),則輸入會按預期連接到{{}}。
爲什麼getterSetter無法正常工作?
感謝您的幫助!
這是代碼:
的javascript:
var app = angular.module('app', [])
.controller('ctrl', ['$scope', function($scope) {
$scope.something = "hahaha";
}])
/*
* attributes:
* - value - a variable to store the input value in
*
*/
.directive('inputNumber', ['$log', function($log) {
var linker = function(scope, element, attrs) {
$log.info('inputNumber linker called! value = "' + scope.value + '".');
scope.getSet = function(newValue) {
if(angular.isDefined(newValue)) {
scope.value = newValue;
}
return scope.value;
}
}
return {
restrict : 'E',
// template: '<p>Say something! {{ value }}</p><input ng-model="value" ng-model-options="{ getterSetter: false }"></input>',
template: '<p>Say something! {{ getSet() }}</p><input ng-model="getSet" ng-model-options="{ getterSetter: true }"></input>',
link: linker,
scope: {
value: '='
}
};
}])
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<h1>Hello Plunker!</h1>
<div ng-app="app" ng-controller="ctrl">
<input-number value="something" ></input-number>
</div>
</body>
</html>
這是欺騙,因爲這樣一來,GETSET功能只用於獲得的價值,而不是將其設置,這意味着它不能檢查它,改變它,或者引起副作用。實際上,如果你這樣做,ng-model-options =「...」根本就沒有必要。 – eltomito 2014-09-04 18:36:13