如题所述
第1个回答 2017-05-18
你这个问题麻烦的地方是 Full Name 这个东西,它无法直接与一个变量绑定。需要手动定义“指令”解决。另外你希望的 setter / getter 也不过是两个“指令”而已。简单实现如下:<!DOCTYPE html><html><head><meta charset="utf-8" /><title>AngularJS</title><script type="text/javascript" src="http://ajax。googleapis。com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><script type="text/javascript" src="http://ajax。googleapis。com/ajax/libs/angularjs/1.0.3/angular.min.js"></script></head><body> <div ng-controller="TestCtrl"> <ul> <li ng-repeat="name in names"> <input type="text" ng-model="name[0]" /> <input type="text" ng-model="name[1]" /> <input type="text" getter="get(name)" setter="set(name, $element)" /> </li> </ul> </div><script type="text/javascript" charset="utf-8">var app = angular.module('Demo', [], angular.noop);app.controller('TestCtrl', function($scope){ $scope.names = [ ['a', 'b'] , ['xx', 'xxx'] , ['xx', 'xxx'] , ['xx', 'xxx'] ]; $scope.get = function(name){ return name[0] + ' ' + name[1]; } $scope.set = function(name, $element){ var p = $element.val().split(' '); name[0] = p[0]; name[1] = p[1]; return; }});app.directive('getter', function($parse){ var link = function($scope, $element, $attrs, $ctrl){ var func = $parse($attrs['getter']); $scope.$watch(function(){ $element.val(func($scope)); }); } return link;});app.directive('setter', function($parse){ var link = function($scope, $element, $attrs, $ctrl){ var func = $parse($attrs['setter']); $element.on('change', function(eventObj){ func($scope, {$element: $element}); $scope.$digest(); }); } return link;});angular.bootstrap(document, ['Demo']);</script></body></html>