AngularJS Directive小實作
以下例子取自官方文件
index.html
<div ng-controller="Controller">
<my-customer info="naomi"></my-customer>
</div>
script.js
angular.module('docsIsolationExample', [])
.controller('Controller', ['$scope', function($scope) {
$scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
$scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' };
}])
.directive('myCustomer', function() {
return {
restrict: 'E',
scope: {
customerInfo: '=info'
},
templateUrl: 'my-customer-plus-vojta.html'
};
});
當中我們可就API等作小改動
angular.module('docsIsolationExample', [])
.controller('Controller', ['$scope', 'someService', function($scope, someService) {
var vm = this;
$scope.data = someService.getSomeData();
$scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
$scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' };
}])
.directive('myCustomer', ['$timeout', function($timeout) {
var templateUrl = '/your/template/path';
return {
require: '^ngModel',
replace: true,
restrict: 'E',
scope: {
ngModel: '=',
customerInfo: '=info'
},
controller: 'Controller',
controllerAs: 'vm',
bindToController: true,
templateUrl: templateUrl,
link: function (scope, elm, attrs, ctrl) {
if (!ctrl) returnl
// In Case this element is a dropdown, use selectpicker refresh to update the display
scope.$watch('vm.isReadOnly', function (newValue, oldValue) {
if (newValue != oldValue) {
$(elm).selectpicker('refresh');
};
});
scope.loadData.then(function (results) {
scope.vm.items = results.data;
$timeout(function () {
scope.$apply(function () {
// Set the default placeholder for the dropdownn list
$(elm).selectpicker({ 'title': 'Select Item' });
});
}, delayTime);
});
}
};
}]);