Angular JS Controller file

//HTML references:
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../SiteAssets/CSS/bootstrap.min.css">
<link href="../SiteAssets/CSS/SPstyles.css" rel="stylesheet" />
<link rel="stylesheet" href="../SiteAssets/font-awesome/font-awesome/CSS/font-awesome.css" />
<link rel="stylesheet" href="../SiteAssets/CSS/homepage.css" />
<script src="../SiteAssets/JS/jquery3.3.1.js"></script>
//Jquery UI - used for custom date picker etc..features
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/smoothness/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>

<script type="text/javascript" src="/_layouts/15/1033/strings.js"></script>
<script type="text/javascript" src="/_layouts/15/SP.RequestExecutor.js"></script>
<script type="text/javascript" src="/_layouts/15/clienttemplates.js"></script>
<script type="text/javascript" src="/_layouts/15/clientforms.js"></script>
<script type="text/javascript" src="/_layouts/15/clientpeoplepicker.js"></script>
<script type="text/javascript" src="/_layouts/15/autofill.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script src="../SiteAssets/Js/SPRibbon.js"></script>
<script src="../SiteAssets/Js/angular.min.js"></script>
<script src="../SiteAssets/Js/angular-sanitize.js"></script>
<script src="../SiteAssets/Js/angular-filter.js"></script>

//Custom date picker input tag
<script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.5.8/es5-shim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.js"></script>
//Your controller js file
<script src="../SiteAssets/Js/customcontroller.js"></script>
//CRUD opertions
<script src="../SiteAssets/Js/factoryDevice.js"></script>
//Custom file upload
<script type="text/javascript" src="../SiteAssets/JS/jquery.multifile.js"></script>

<body>
<!--Attachment upload button-->
<div class="form-group"> <label for="">Attachment</label> <div class="datepickerinput"> <input id="file_input" type="file" name="files[]" ng-model="file_input"> </div> </div>
<!--Bootstrap model popup-->
<div class="btnnewtask btn" ng-click="openPopUp()" data-toggle="modal" data-target="#exampleModal">
<i class="fa fa-plus-circle" aria-hidden="true"></i>Open popup
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" ng-click="closepopup()">&times;</button>
<h4 class="modal-title">Here is header</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="">Project Name</label>
<input type="text" class="form-control" id="" placeholder="Enter project name">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal"
ng-click="addItemToList()">Save</button>
</div>
</div>
</div>
</div>
<div class="modelpop"></div>
</body>
var app = angular.module('myApp', ['angular.filter']) //, 'ngTagsInput'
app.controller('allItemsCntrl', ["$scope""$filter""$http""$sce""RESTService"function ($scope$filter$http$sceRESTService) {
//site URL
$scope.siteURL = _spPageContextInfo.webAbsoluteUrl;
$scope.pageLoad = function(){ setTimeout(function(){ $('#file_input').multifile(); },1000); }
//CRUD - Read
$scope.readDataFromFactoryServices = function(){ $scope.QueryData = "$select=*,ProductProject/ID,ProductProject/Title&$expand=ProductProject&$filter=ProductProject/Id eq "+$scope.projectIDURL+"&$orderby=Modified desc"; RESTService.getItems("ListName", $scope.QueryData).then(function (response) { $scope.mydata = response; }); }
//CRUD - Read list file attachment
$scope.loadProjects = function () {
$scope.ProductProjectURL = "$select=*,ProjectLead/Name,ProjectLead/EMail,ProjectLead/Title,ProjectLead/Id&$expand=ProjectLead&$orderby=Modified desc";
RESTService.getItems("ProductProject", $scope.ProductProjectURL).then(function (response) {
$scope.productProjectListData = response;
angular.forEach($scope.productProjectListData, function(item1,index){
$scope.docURL = "(" + item1.ID + ")/AttachmentFiles"
RESTService.getAttachements("ProductProject", $scope.docURL).then(function (response) {
if(response.length!=0){
angular.forEach(response, function(item,index){
item1.FileLeafRef = item.FileName;
item1.FileRef = item.ServerRelativeUrl;
});
}
});  
});
});
}
//CRUD - ADD list item
$scope.saveFunding = function () {
$scope.saveJSONItemdata = {
__metadata: {
type: "SP.Data.GeneralInvestmentCostResultsListItem"
},
Title: "",
ProductProjectId: $scope.projectIDURL,
QualityGatesId: $scope.qualityGateIDURL,
GeneralInvestmentCostJSON: JSON.stringify($scope.caliculatedvalues)
};
RESTService.addItem($scope.saveJSONItemdata, "GeneralInvestmentCostResults").then(function (response) {
alert("Saved successfully");
});
}
//CRUD - UPdate List Item
$scope.updateFunding = function () {
$scope.updateJSONItemdata = {
__metadata: {
type: "SP.Data.GeneralInvestmentCostResultsListItem"
},
ID: $scope.readFundingInfo[0].ID,
Title: "",
ProductProjectId: $scope.projectIDURL,
QualityGatesId: $scope.qualityGateIDURL,
GeneralInvestmentCostJSON: JSON.stringify($scope.caliculatedvalues)
};
RESTService.postItem($scope.updateJSONItemdata, "GeneralInvestmentCostResults").then(function (response) {
alert("Updated successfully");
$scope.readCaliculationsFlag = true;
$scope.readFunding();
});
}

//Decimal value render 2 digits
$scope.renderDecimal = function (n) {
//return Math.floor(n * 100) / 100;
var multiplier = Math.pow(10, 2 || 0);
return Math.round(n * multiplier) / multiplier;
}
//global variables var arraycount = 0; var fileUploadeCount = 0; //Upload list attachment code //First we need to add item to a list before uploading attachment $scope.addItemToList = function(){ var fileArray = []; $("#file_input").each(function () { if ($(this)[0].files[0]) { fileArray.push({ "Attachment": $(this)[0].files[0] }); } }); arraycount = fileArray.length; $scope.dataJSON = { __metadata: { type: "SP.Data.ProductProjectListItem" }, Title: $scope.projectName?$scope.projectName:"", ProjectLeadId: $scope.projectLeadUserId, PlannedStartDate: $scope.projectStartDate?$scope.projectStartDate:"" }; RESTService.addItem($scope.dataJSON, "YourListName").then(function (response) { console.log("Item created successfully in List"); console.log(response); var id = response.d.Id; if (fileArray.length != 0) { for (i = 0; i <= fileArray.length - 1; i++) { $scope.loopFileUpload("ProductProject", id, fileArray, i).then( function () {}, function (sender, args) { alert("Error in uploading attachment"); dfd.reject(sender, args); } ); } } }); } $scope.loopFileUpload = function(listName, id, fileArray, fileCount){ $("#preloader").show(); var dfd = $.Deferred(); $scope.uploadFile(listName, id, fileArray[fileCount].Attachment); return dfd.promise(); } $scope.uploadFile = function(listname, ID, file) { var getFileBuffer = function (file) { var deferred = $.Deferred(); var reader = new FileReader(); reader.onload = function (e) { deferred.resolve(e.target.result); } reader.onerror = function (e) { deferred.reject(e.target.error); } reader.readAsArrayBuffer(file); return deferred.promise(); }; getFileBuffer(file).then(function (buffer) { $.ajax({ url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listname + "')/items(" + ID + ")/AttachmentFiles/add(FileName='" + file.name + "')", method: 'POST', async: false, data: buffer, processData: false, headers: { "Accept": "application/json; odata=verbose", "content-type": "application/json; odata=verbose", "X-RequestDigest": document.getElementById("__REQUESTDIGEST").value }, success: onAttachmentSucess }); }); function onAttachmentSucess() { fileUploadeCount++; if (arraycount == fileUploadeCount) { console.log('attachment uploaded successfully'); $("#preloader").fadeOut('slow'); } } } //SharePoint model popup $scope.addnewProductProject = function(){ var options = { url: $scope.siteURL + '/Lists/ProductProject/NewForm.aspx?Source=https://team.uat.sp.wp.corpintra.net/sites/07467/LP/SitePages/homepage.aspx', title: 'Create Product Project', allowMaximize: false, showClose: true, width: 600, height: 400 }; SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', options); return false; } //bootstrap model popup //To open popup $scope.openPopUp = function(){ setTimeout(function(){ $("div").removeClass('modal-backdrop fade in'); $('#exampleModal').trigger('focus'); $(".modelpop").addClass("modal-backdrop fade in"); },1000); } $scope.closepopup = function(){ $("#preloader").show(); setTimeout(function(){ $("div").removeClass('modal-backdrop fade in'); $("#preloader").fadeOut('slow'); },1000); }
}]).controller('htmlCtrl', ['$scope''$http''$sce'function ($scope$http$sce) {
        $scope.renderHtml = function (htmlCode) {
            return $sce.trustAsHtml(htmlCode);
        };
        $scope.renderUrl = function (htmlCode) {
            return $sce.trustAsResourceUrl(htmlCode);
        };
    }])
    .filter('unique'function () {
        return function (inputkey) {
            var unique = {};
            var uniqueList = [];
            if (input != undefined) {
                for (var i = 0i < input.lengthi++) {
                    if (typeof unique[input[i][key]] == "undefined") {
                        unique[input[i][key]] = "";
                        uniqueList.push(input[i]);
                    }
                }
                return uniqueList;
            }
        };
    })
    .filter('groupBy', ['$parse''pmkr.filterStabilize'function ($parsefilterStabilize) {
        function groupBy(inputprop) {
            if (!input) {
                return;
            }
            var grouped = {};
            input.forEach(function (item) {
                var key = $parse(prop)(item);
                grouped[key] = grouped[key] || [];
                grouped[key].push(item);
            });
            return grouped;
        }
        return filterStabilize(groupBy);
    }])
//custom date picker field
.directive('datePicker'function(){
        return{
          restrict: 'A',
          require: 'ngModel',
          link: function(scopeelmattrctrl){
            
            // Format date on load
            ctrl.$formatters.unshift(function(value) {
              if(value && moment(value).isValid()){
                   return moment(new Date(value)).format('MM/DD/YYYY');
              }
              return value;
            })
            
            //Disable Calendar
            scope.$watch(attr.ngDisabledfunction (newVal) {
              if(newVal === true)
                $(elm).datepicker("disable");
              else
                $(elm).datepicker("enable");
            });
            
            // Datepicker Settings
            elm.datepicker({
              autoSize: true,
              changeYear: true,
              changeMonth: true,
              dateFormat: attr["dateformat"] || 'mm/dd/yy',
              showOn: 'button',
              buttonText: '<i class="glyphicon glyphicon-calendar"></i>',
              onSelect: function (valu) {
                scope.$apply(function () {
                    ctrl.$setViewValue(valu);
                });
                elm.focus();
              },
                beforeShow: function(){
                if(attr["minDate"] != null)
                    $(elm).datepicker('option''minDate'attr["minDate"]);
                  
                if(attr["maxDate"] != null )
                    $(elm).datepicker('option''maxDate'attr["maxDate"]);
              },
            });
          }
        }
      });

Comments