在PartialView angularjs控制器不工作(angularjs controller

2019-10-20 14:37发布

我有一个观点,其包含一个链接调用PartialView。

<div data-ng-controller="MainController">
    <a href="#" data-ng-click=callPartialView()">
        Click here to see the details.
    </a>
</div>

<script>
    app.controller('MainController', ['$scope', 'HttpService', 
        function($scope, HttpService) {

        $scope.callPartialView = function() {
            HttpService.getModal('/Controller/ShowModalMethod', {});
        };
    }]);
</script>

我HttpService的服务具有调用来自控制器的作用,以显示它返回一个PartialView功能。

getModal = function(url, params) {
    $http.get(url, params).then(function(result) {
        $('.modal').html(result);
    });
}

所述PartialView是完全示出。 当我尝试将控制器添加到PartialView内容将出现问题。

<div class="wrapper" data-ng-controller="PartialViewController">
    <span data-ng-bind="description"></span>
</div>

<script>
    alert('This alert is shown.');
    app.controller('PartialViewController', ['$scope', 'HttpService', 
        function($scope, HttpService) {

        $scope.description = "That's the content must have to appear in that bind above, but it isn't working properly.";
    }]);
</script>

控制器与预期不工作。 无我把控制器内出现在上述股利。 发生了什么? 谢谢你们!

Answer 1:

停止使用jQuery ...

问题是, $('.modal').html(result); 只添加HTML的东西用.modal类。 你需要做的是使用AngularJS,像编译模板:

app.factory('HttpService', function($document, $compile, $rootScope, $templateCache, $http) {

    var body = $document.find('body');

    return {
        getModal: function (url, data) {

            // A new scope for the modal using the passed data
            var scope = $rootScope.$new();
            angular.extend(scope, data);

            // Caching the template for future calls
            var template = $http.get(url, {cache: $templateCache})
                .then(function (response) {

                    // Wrapping the template with some extra markup
                    var modal = angular.element([
                        '<div class="modal">',
                        '<div class="bg"></div>',
                        '<div class="win">',
                        '<a href="#" class="icon cross"></a>',
                        '<div>' + response.data + '</div>',
                        '</div>',
                        '</div>'
                    ].join(''));

                    // The important part
                    $compile(modal)(scope);
                    // Adding the modal to the body
                    body.append(modal);

                    // A close method
                    scope.close = function () {

                        modal.remove();
                        scope.destroy();
                    };
                });
        }
    };
});

工作实例

http://jsfiddle.net/coma/6j66U/



文章来源: angularjs controller in PartialView not working