在动态添加时,角度代码在指令内部不起作用?

时间:2015-05-06 10:10:47

标签: javascript jquery angularjs

我正在动态添加Angular指令内容,但我无法在其中添加$scopeController等功能。我该如何解决这个问题?例如:

a.html

<div ng-controller="actrl">{{aname}}</div>

b.html

<div ng-controller="bctrl">{{bname}}</div>

假设我有一个带有模板URL的指令:/a.html和 我动态地将其更改为/b.html,然后对于b.html,角度功能(bctrl)无效。

的jQuery

jQuery.ajax({
  url: menu.templateUrl,
  success: function(response) {                   
    jQuery("view-partial").html(response);                      
  }
});

4 个答案:

答案 0 :(得分:1)

使用ng-view

包含这样的内容
 $routeProvider
      .when('#/a.html', {
        templateUrl: 'b.html',
        controller: 'bctrl',

      });

以下是您的问题的解决方案 检查链接 http://jsbin.com/voyeki/2/edit

我的代码是

.controller("myCtrl",function($scope,$compile){
angular.element("view-partial").html($compile(response)($scope));
});

希望这是您的问题的解决方案: - )

答案 1 :(得分:0)

无需在视图上使用$scope

<div ng-controller="actrl">{{$scope.aname}}</div>

您需要直接使用aname

<div ng-controller="actrl">{{aname}}</div>

答案 2 :(得分:0)

HTML Code:
 <view-partial></view-partial>  
JS Code: 

jQuery.ajax({url: menu.templateUrl,
            success: function(response) {                   
            jQuery("view-partial").html(response);                      
                    }
        });

答案 3 :(得分:0)

Main.js 例如

   <script>  

        var bosAppModule = angular.module("bosApp", []); 

        $http({
                 url: menu.templateUrl,
                  method: "GET"              
             }).success(function(data, status) {
              $scope.data = data;
             jQuery("view-partial").html($compile($scope.data)($scope));
                              }).error(function(data, status) {
                               $scope.status = status;
            });
        bosAppModule.controller('Controller2', ['$scope', function($scope) {
            $scope.support = {
              name: 'bagya',
              address: 'bangalore'
            };   
        }]);    
    </script>
Partial page
  <div  ng-controller="Controller2">
    <h1>Hello {{support.name}}</h1>
    </div>

现在它正在工作,如果控制器代码主js文件。如果部分页面中的控制器代码不起作用。请查看以下代码并帮助我解决此问题。

例如

<div  ng-controller="Controller2">
<h1>Hello {{support.name}}</h1>
</div>
<script>
bosAppModule.controller('Controller2', ['$scope', function($scope) {
    $scope.support = {
      name: 'bagya',
      address: 'bangalore'
    };   
}]);
</script>

实际上我需要在那个部分页面中使用evey控制器。