简体   繁体   English

使用两个不同的控制器文件时,局部视图ng-click不起作用

[英]Partial view ng-click not working when using two different controller files

I am working on MVC4 with angular JS and using ng-include to call a partial view inside my main view. 我正在使用Angular JS开发MVC4,并使用ng-include调用主视图内的局部视图。 Issue comes when I am trying to click a button inside my partial view. 当我尝试单击局部视图内的按钮时出现问题。

I have two different controllers in angular, one for main and other one for a partial view both are working under same module. 我有两个角度不同的控制器,一个用于主控制器,另一个用于局部视图,两者都在同一模块下工作。

My file structure is as follows 我的文件结构如下

Scripts.. 脚本..

| | --Main.js --Main.js

|--ProjectPage.js | --ProjectPage.js

(Main.js) (Main.js)

var app = angular.module("Layout", []);
app.controller("LoadPage", function ($scope) {
    $scope.templateUrl = '/Home/DefaultPage';
};

(ProjectPage.js) (ProjectPage.js)

angular.module("Layout")
    .controller("CNTRL", function ($scope) {
    $scope.clickBtn1 = function () {
        alert("ABU");
    };
  });

and this is the HTML, I am using for partial page 这是HTML,我正在使用部分页面

<body ng-app="Layout" ng-controller="CNTRL">
<button ng-click="clickBtn1 ()" id="click">click</button>

The partial view is working fine when its called up independently(not inside the main view). 当单独调用局部视图时,局部视图工作正常(不在主视图内部)。 No error is coming inside the browser but click event is not working. 浏览器内部没有错误,但click事件不起作用。

The problem is probably because you are calling the "app" twice. 问题可能是因为您两次调用“应用程序”。 Once in your layout (html) page and then in your partial page. 进入布局(html)页面,然后进入部分页面。 You can fix this by replacing: 您可以通过以下方式解决此问题:

<body ng-app="newLayout" ng-controller="CNTRL">

With: 附:

<div ng-controller="CNTRL">
  <!-- button code here -->

NOTE: The change from body to div (can be any html container tag) and removal of ng-app directive. 注意:body更改为div (可以是任何html容器标记),并删除了ng-app指令。

Here! 这里! You have same module name so it will consider first one. 您具有相同的模块名称,因此它将考虑第一个。 Just different name both and it will works.. 两者都有不同的名称,它将起作用。

main.js main.js

var app = angular.module("Layout", []);
app.controller("LoadPage", function ($scope) {
    $scope.templateUrl = '/Home/DefaultPage';
};

ProjectPage.js ProjectPage.js

angular.module("newLayout")
    .controller("CNTRL", function ($scope) {
    $scope.clickBtn1 = function () {
        alert("ABU");
    };
});

Body content 身体内容

<body ng-app="newLayout" ng-controller="CNTRL">
<button ng-click="clickBtn1 ()" id="click">click</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM