Search code examples
angularjssharepointweb-parts

How to Initialize SharePoint Script Editor WebPart Content using AngularJS


I am having a problem getting initial values to bind using a SharePoint Script WebPart and AngularJS. I have tried all the different ways to initialize ng-int, custom init function, document ready. In all cases the function is being called and values set but the UI is not updating with the values until I interact with the controller again.

In the code below it is the {{usertitle}} that does not bind.

So the direct question would be what is the proper way to successfully Initialize values in the context of SharePoint, Script WebPart, and AngularJS?

Just to show what the UI does look like after load, other bindings are populated but not usertitle. enter image description here

Click Next Button and then Previous (function is not called during this).

enter image description here

HTML in Script Editor

<div id="appDiv" ng-app="myapp">
        <div id="controllerDiv" ng-controller="MyController" >
                <div class="item10 mainborder">
                    <div ng-show=showPage1() ng-init="firstFunction(this)">
                            <p class="lead">Welcome {{usertitle}}!</p>
                    </div>
                    <div>
                        <input type="button" value="Previous" ng-click="pagePrevious()" ng-disabled=showPage1() />
                        <span>{{pageXofY()}}</span>
                        <input type="button" value="Next" ng-click="pageNext()" ng-disabled=showPage6() />
                    </div>
                </div>
        </div>
    </div>

Angular Controller JS

        $scope.firstFunction = function ($scope) {
            //User Info-------------------------------------
            var userid = _spPageContextInfo.userId;
            var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";

            var requestHeaders = { "accept": "application/json;odata=verbose" };
            $.ajax({
                url: requestUri,
                contentType: "application/json;odata=verbose",
                headers: requestHeaders,
                success: onSuccessUInfo,
                error: onErrorUInfo
            });

            function onSuccessUInfo(data, request) {
                $scope.usertitle = data.d.Title;
                $scope.email = data.d.Email;
                $scope.loginname = data.d.LoginName;
                //alert(loginName);
            }

            function onErrorUInfo(error) {
                alert("error");
            }

        //End USeriNfo------------------------------------
        };


Solution

  • Previous tested demo here, hope it helps you.

    <script type="text/javascript" src="/sites/Developer/SiteAssets/angular.min.js"></script>
        <script type="text/javascript">
            window.onload = function () {
                //   alert('pease select IT');
            };
    
            var app = angular.module('pageLoadApp', []);
            app.controller('ContactsUpdate', function ($scope) {
                $scope.contact = { firstName: "", lastName: "", Location: "", Departmant: "" };
                $scope.UpdateContact = function ($event) {
                    var x = $scope.contact;
                    $event.preventDefault();
    
                    //if (x.Departmant == "HR") {
                    //    alert('pease select IT , This is update');
                    //}
                    //else {
                    var clientContext = new SP.ClientContext.get_current();
                    var web = clientContext.get_web();
                    var list = web.get_lists().getByTitle('ContactDetails');
    
                    //this.oListItem = list.getItemById(9);
                    var listItem = list.getItemById(1);
    
                    listItem.set_item('Title', 'My new updated Title');
    
                    //  listItem.set_item('Title', x.firstName);
                    listItem.set_item('firstName', x.firstName);
                    listItem.set_item('lastName', x.lastName);
                    listItem.set_item('fullName', x.firstName + " " + x.lastName);
                    listItem.set_item('Location', x.Location);
                    listItem.set_item('Departmant', x.Departmant);
                    alert(listItem.get_item('Title'));
    
                    listItem.update();
    
                    clientContext.executeQueryAsync(
                       Function.createDelegate(this, onQuerySucceededUpdate),
                       Function.createDelegate(this, onQueryFailedUpdate)
                       );
                }
                SP.SOD.executeFunc('sp.js', 'SP.ClientContext', (function () {
                    var clientContext = new SP.ClientContext.get_current();
                    var web = clientContext.get_web();
                    var list = web.get_lists().getByTitle('ContactDetails');
    
                    //this.oListItem = list.getItemById(9);
                    var listItem = list.getItemById(1);
                    clientContext.load(listItem);
                    clientContext.executeQueryAsync(function () {
                        $scope.$apply(function () {
                            $scope.contact = { firstName: listItem.get_item('firstName'), lastName: listItem.get_item('lastName'), Location: listItem.get_item('Location'), Departmant: listItem.get_item('Departmant') };
                        });
                    },
                    function (sender, args) {
                        console.log("An error occurred when deletion");
                    });
                }));
            })
    
            onQuerySucceededUpdate = function () {
                alert('Successfully updated the contact');
            }
    
            onQueryFailedUpdate = function (sender, args) {
                alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
            }
    
        </script>  
    <h1>Contact Information:</h1>  
    <br />  
    <div >  
    
        <div ng-app="pageLoadApp" ng-controller="ContactsUpdate">  
            <strong>First Name</strong>  
            <input type="text" ng-model="contact.firstName" /><br />  
            <br />  
            <strong>Last Name</strong>   
            <input type="text" ng-model="contact.lastName" /><br />  
            <br />  
            <strong>Location&nbsp;&nbsp;</strong> <input type="text" ng-model="contact.Location" /><br />  
            <br />  
            <strong>Departmant</strong>     
    
            <select id="Departmant" ng-model="contact.Departmant" >
                <option>HR</option>
                <option>IT</option>
    
            </select><input type="submit" value="Submit" ng-click="UpdateContact($event)" />  
        </div>  
    </div>