带有JQuery延迟的SharePoint 2013中的异步调用

时间:2015-03-27 08:51:19

标签: jquery angularjs asynchronous sharepoint-2013

大家好我获得$ scope值有问题。我想通过使用AngularjS显示值。

var deferred = $.Deferred();
var items;
var json;
//App.js
$(document).ready(function () {
    retrieveListItems();
});

function retrieveListItems() {
    var siteCollectionUrl = '/sites/DeverloperSite/';
    var context = new SP.ClientContext(siteCollectionUrl);
    var list = context.get_web().get_lists().getByTitle("StudentList");

    var queryText = "<Query><Where><And><IsNotNull><FieldRef Name='Title' /></IsNotNull><IsNotNull><FieldRef Name='School' /></IsNotNull></And> </Where></Query>";
    var query = new SP.CamlQuery();
    query.set_viewXml(queryText);
    items = list.getItems(query);
    context.load(items);
    context.executeQueryAsync(
        function retrieveListItemSuccess() {
            var listDetails = "";
            var listEnumerator = items.getEnumerator();
            while (listEnumerator.moveNext()) {
                var listItem = listEnumerator.get_current();
                //list Details is String Object
                listDetails += '{"id":"' + listItem.get_id() + '","name":"' + listItem.get_item("Title") + '","school":"' + listItem.get_item("School") + '","gender":"' + displayGender(listItem.get_item("Gender")) + '"},';
            }
            var stringObject = listDetails.substring(0, listDetails.length - 1);//string object and remove the last comma ','
            deferred.resolve(stringObject);
        },
        function retrieveListItemFail(sender, args) {
            alert("error in inner request: " + args.get_message());
        }
    );
}

这是stringObject值 '{"id":"1","name":"Nang Thang Hai","university":"Hutech University","gender":"true"},{"id":"2","name":"Gio Thang Chin","university":"Foreign Trade University","gender":"false"}'

var myApp = angular.module('myApp', []);
myApp.controller("myController", function ($scope) {
    deferred.done(function (value) {
        alert(value);//passing sucess here
        json = $.parseJSON('[' + value + ']');//convert string object to json data      
        alert("Name:"+json[0].name);//Nang Thang Hai
    });
$scope.students = json;//why there is nothing here ? 
});

如果我在deferred.done方法中移动控制器。它不起作用,因为它在Jquery里面。我知道方法context.executeQueryAsync()是异步的,所以我认为我们必须先推迟它然后再执行angularjs。

var myApp = angular.module('myApp', []);
deferred.done(function (value) {        
    myApp.controller("myController", function ($scope) {//Error angularjs can't put inside jquery...
        var json = $.parseJSON('[' + value + ']');//convert string to json data   
        $scope.students = json;
    });
});



<table id="tbStudent" data-ng-app="myApp" data-ng-controller="myController">
        <tbody>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>School</th>
                <th>Gender</th>
            </tr>
            <tr data-ng-repeat="student in students">
                <td>{{student.id}}</td>
                <td>{{student.name}}</td>
                <td>{{student.school}}</td>
                <td>{{student.gender}}</td>
            </tr>
        </tbody>
    </table>

感谢您的帮助。你的意见正在帮助我发展自己的事业:)

2 个答案:

答案 0 :(得分:0)

您无法将控制器包装在返回的promise中,以下代码不起作用

var myApp = angular.module('myApp', []); 
    deferred.done(function (value) {  
    // Doesn't work <----
    myApp.controller("myController", function ($scope) {//Error angularjs can't put inside jquery...
        var json = $.parseJSON('[' + value + ']');//convert string to json data   
        $scope.students = json;
    }); 
});

在此尝试中,您无法看到任何内容,因为延迟是异步,启动时$scope.students为空。您必须移动$scope.students内的.done以填充数据

var myApp = angular.module('myApp', []);
myApp.controller("myController", function ($scope) {
    deferred.done(function (value) {
        alert(value);//passing sucess here
        json = $.parseJSON('[' + value + ']');//convert string object to json data      
        alert("Name:"+json[0].name);//Nang Thang Hai
        $scope.students = json; // Now you have data on your scope var
    });
// $scope.students = json; // why there is nothing here ? Because the deferred 
// is not resolved, you must move this inside the .done function
});

Angular框架还包含用于与其他源交互的Service,Factory和Provider,在这种情况下,最好将retrieveListItems包装在服务中并将其注入控制器。

我写了下面的代码,但我无法测试它。 您可以了解服务和角网站上的公司,请检查thisthis

var myApp = angular.module('myApp', []);

myApp.service("myService", 
    ['$q',
        function($q){

            function displayGender(gender){
                // TODO Implement ?
                return gender;
            }

            var service = {
                retrieveListItems: function(){

                    var deferred = $q.defer();

                    var siteCollectionUrl = '/sites/DeverloperSite/';
                    var context = new SP.ClientContext(siteCollectionUrl);
                    var list = context.get_web().get_lists().getByTitle("StudentList");

                    var queryText = "<Query><Where><And><IsNotNull><FieldRef Name='Title' /></IsNotNull><IsNotNull><FieldRef Name='School' /></IsNotNull></And> </Where></Query>";
                    var query = new SP.CamlQuery();
                    query.set_viewXml(queryText);
                    var items = list.getItems(query);
                    context.load(items);
                    context.executeQueryAsync(
                        function retrieveListItemSuccess() {
                            var listDetails = [];
                            var listEnumerator = items.getEnumerator();
                            while (listEnumerator.moveNext()) {
                                var listItem = listEnumerator.get_current();
                                //list Details is String Object
                                listDetails.push(
                                    {
                                        id : listItem.get_id(),
                                        name: listItem.get_item("Title"),
                                        school: listItem.get_item("School") ,
                                        gender: displayGender(listItem.get_item("Gender")) 
                                    }
                                );
                            }

                            deferred.resolve(listDetails);
                        },
                        function retrieveListItemFail(sender, args) {
                            deferred.reject(args.get_message());
                        }
                    );

                    return deferred.promise;
                }
            };

            return service;
        }
    ]
);

myApp.controller("myController", ['$scope', 'myService', '$log', function ($scope, myService, $log) {

    myService.retrieveListItems().then(
        function(items){
            $scope.students = items;
        },
        function(error){
            $log.error("Error in retrieveListItems: " + error);
        }
    );

}]);

答案 1 :(得分:0)

以下是使用Sharepoint 2013 Javascript和AngularJS的答案

$(document).ready(function () {
//we don't need to use jquery here. Angular will call itself
});

function retrieveListItems() {
    var deferred = $.Deferred();
    var siteCollectionUrl = '/sites/DeverloperSite/';//   kbui6.sharepoint.com/sites/DeverloperSite/
    var context = new SP.ClientContext(siteCollectionUrl);
    var list = context.get_web().get_lists().getByTitle("StudentList");

    var queryText = "<Query><Where><And><IsNotNull><FieldRef Name='Title' /></IsNotNull><IsNotNull><FieldRef Name='School' /></IsNotNull></And> </Where></Query>";
    var query = new SP.CamlQuery();
    query.set_viewXml(queryText);
    items = list.getItems(query);
    context.load(items);
    context.executeQueryAsync(
        function retrieveListItemSuccess() {
            var listDetails = "";
            var listEnumerator = items.getEnumerator();
            while (listEnumerator.moveNext()) {
                var listItem = listEnumerator.get_current();
                //list Details is String Object
                listDetails += '{"id":"' + listItem.get_id() + '","name":"' + listItem.get_item("Title") + '","school":"' + listItem.get_item("School") + '","gender":"' + displayGender(listItem.get_item("Gender")) + '","email":"'+listItem.get_item("Email")+'"},';
            }
            var stringObject = listDetails.substring(0, listDetails.length - 1);//string object
            deferred.resolve(stringObject);
        },
        function retrieveListItemFail(sender, args) {
            alert("error in inner request: " + args.get_message());
        }
    );
    return deferred;
}

//Angular Code
var myApp = angular.module('myApp', []);
myApp.controller("myController", function ($scope) {
    $.when(retrieveListItems()).done(function (value) {
        json = $.parseJSON('[' + value + ']');//convert string to json data      
        $scope.students = json;
        //scope was not updated so we need to push it in
        if (!$scope.$$phase) {
            $scope.$apply();
        }       
    }); 

将数据从列表显示为HTML代码

<table id="tbStudent" data-ng-app="myApp" data-ng-controller="myController">
        <tbody>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>School</th>
                <th>Gender</th>
            </tr>
            <tr data-ng-repeat="student in students">
                <td>{{student.id}}</td>
                <td>{{student.name}}</td>
                <td>{{student.school}}</td>
                <td>{{student.gender}}</td>
            </tr>
        </tbody>
    </table>