How can I create an isolated scope in a controller to make a reusable directive? Take a look at my code snippet below:
(function (app) {
// Declare the Template
var template = function (element, attrs) {
var htmltext =
'<select ' + attrs.type +
' ng-init="getAll(\'' + attrs.classname +
'\');" ng-model="' + attrs.model +
'" ng-options="value.' + attrs.data +
' for value in result"></select>';
return htmltext;
};
app.directive('listData', function () {
return {
restrict: 'E',
controller: 'listController',
controllerAs: 'vm',
scope: { vm: '=' },
template: template
}
});
}(angular.module('app')));
Is it possible to utilize this directive multiple times with just one controller and access the resulting data from controller functions? In the example provided, there is a getAll
function that returns $scope.result
from the controller to the caller. This returned result is intended to be used with the ng-model
assigned to each directive.
<div ng-controller="listController">
<list-data type=""
model="person"
classname="Person"
data="Family"
vm="listController">
</list-data>
<list-data></list-data>
<p>{{person.Name}} {{person.Family}}?</p>
Here is the list controller:
(function (app) {
app.controller('listController', ['$scope','myservice',function ($scope, myservice) {
// Call GetAll Method From Each Class
$scope.getAll = function (classname) {
myservice.getAll(classname)
.success(function (data, status) {
$scope.result = data;
$scope.status = status;
})
.error(function (data, status) {
$scope.result = data;
$scope.status = status;
});
}
}(angular.module('app')));
And here is the service:
(function (app) {
app.factory('myservice', function ($http,$q) {
return {
getAll: function (classname) {
try {
return $http.get('/api/' + classname + '/GetAll/');
} catch (e) {
window.alert(e.message);
// Should send an error to controller
}
}
}
});
}(angular.module('app')));