简体   繁体   中英

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. 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

|--ProjectPage.js

(Main.js)

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

(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

<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.

The problem is probably because you are calling the "app" twice. Once in your layout (html) page and then in your partial page. 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.

Here! You have same module name so it will consider first one. Just different name both and it will works..

main.js

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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