angular.js实现省市区三级联动指令

不多说,直接上代码,一开始搞了好久,最后才弄懂,希望对大家有帮助

1.jade

div.col-md-2
select.form-control(ng-options="value.code as value.name for value in provincial" ng-model="info.provincial" required='' ng-change="getArea('city',info.provincial)")
option(value='') 选择省
div.col-md-2
select.form-control(ng-options="value.code as value.name for value in city" ng-model="info.city" required='' ng-change="getArea('district',info.city)")
option(value='') 选择市
div.col-md-2
select.form-control(ng-options="value.code as value.name for value in district" ng-model="info.district" required='' ng-change="areaText()")
option(value='') 选择区

js

  

  传的值angular.js实现省市区三级联动指令

  后台返回的数据 省

  angular.js实现省市区三级联动指令

  

  传的值angular.js实现省市区三级联动指令

  后台返回的数据 市

  angular.js实现省市区三级联动指令

angular.module('app').directive('provinceSelect', ['$rootScope', 'api', function($rootScope, api) {
// Runs during compile
'use strict';
return {
// name: '',
// priority: 1,
// terminal: true,
scope: {
info: '=info',
area: '=area'
}, // {} = isolate, true = child, false/undefined = no change
controller: function($scope, $element, $attrs, $transclude) {
function getArea(id, returnFn) {
api("areaList", { //后台给的省市区接口
data: {
parentId: id
}
}).then(function(data) {
returnFn(data);
});
}
$scope.getArea = function(name, id) {
if (name === 'city' && id === undefined) {
$scope.city = [];
$scope.district = [];
return;
} else if (name === 'district' && id === undefined) {
$scope.district = [];
return;
}
getArea(id || 0, function(data) {
$scope[name] = data;
});
};
$scope.getArea('provincial', 0);
$scope.$watch('info', function(newVal, oldVal) {
if (newVal) {
$scope.getArea('city', newVal.provincial);
$scope.getArea('district', newVal.city); }
});
// provincialWatch();
// if ($scope.info.provincial) {
// $scope.getArea('city', $scope.provincial);
// }
// if ($scope.info.district) {
// $scope.getArea('district', $scope.city);
// }
$scope.areaText = function() {
var area = $element.find("select");
var areas = '';
for (var i = 0; i < area.length; i++) {
var index = area[i].selectedIndex;
if (index === 0) {continue;}
areas += area[i].options[index].text;
}
$scope.area = areas;
};
},
// require: 'ngModel', // Array = multiple requires, ? = optional, ^ = check parent elements
// restrict: 'A', // E = Element, A = Attribute, C = Class, M = Comment
// template: '',
templateUrl: 'app/dist/directive/provinceSelect/provinceSelect.html',
// replace: true,
transclude: true,
// compile: function(tElement, tAttrs, function transclude(function(scope, cloneLinkingFn){ return function linking(scope, elm, attrs){}})),
link: function($scope, iElm, iAttrs, controller) {
//console.log($scope)
}
};
}]);
上一篇:日志分析(php+nosql+rsync+crontable)


下一篇:android 启动adb