我创建了一个简单的 angularjs 指令来输入城市和邮政编码。它工作得很好,除非我在同一个控制器中使用它两次,输入字段中的值是重复的!我相信这是一个范围问题,但我不知道如何解决?
FDVilleModule = angular.module('FDVille', []).
directive('fdVille', () ->
return {
restrict: 'E'
require: 'ngModel'
template: """
<div class=\"row-fluid\">
<div class=\"span4\">
<input
ng-model=\"cp\"
ng-change=\"edit()\"
maxlength=\"5\"
type=\"text\"
class=\"input-block-level\"
placeholder=\"Code Postal\" />
</div>
<div class=\"span8\">
<select ng-model=\"selected_ville\"
ng-options=\"v.id as v.nom for v in villes\"
class=\"input-block-level\">
</select>
</div>
</div>"""
link: (scope, elem, attr, ctrl) ->
scope.$watch('selected_ville', (value)->
ctrl.$setViewValue(value))
controller: ($scope) ->
download_villes = (cp) -> $.getJSON('/ws/villes/cp', {cp:cp}, set_data)
download_villesid = (id) -> $.getJSON('/ws/villes/id', {id:id}, set_init_data)
set_data = (results) ->
$scope.villes = results
$scope.selected_ville = results[0].id if results.length
$scope.$apply()
saved_cp = ""
$scope.edit = () ->
if isNaN($scope.cp)
$scope.cp = saved_cp
else
saved_cp = $scope.cp
if saved_cp.length == 5
download_villes(saved_cp)
else
$scope.selected_ville = null
$scope.villes = []
}
)