0

我無法獲取部分div的ng-click屬性來觸發我想要的功能,名爲testDivClicked()連接ng-click到控制器功能

在我的應用程序控制器,我提供給部分路線稱爲test

(function() { 
    "use strict"; 

    angular 
     .module('myApp', ['ngRoute', 'ui.bootstrap', 'myApp.main', 'myApp.test']) 
     .config(config); 

    config.$inject = ['$routeProvider']; 

    function config($routeProvider) { 
     $routeProvider 
      .when('/', {templateUrl: '/partials/main.html', controller: 'MainController', controllerAs: 'vm'}) 
      .when('/test', {templateUrl: '/partials/test/test.html', controller: 'TestController', controllerAs: 'vm'}) 
      .otherwise({redirectTo: '/'}); 
    } 
})(); 

這裏是test.html部分是被插入到父視圖:

<div class="outer-holder test-outer-holder"> 
    <div class="middle-holder test-middle-holder"> 
     <div class="inner-holder test-inner-holder"> 
      <div class="test-container" ng-click="vm.testDivClicked('test-container')"> 
       <legend>Test</legend> 
      </div> 
     </div> 
    </div> 
</div> 

test控制器:

(function() { 
    "use strict"; 

    angular 
     .module("myApp.test") 
     .controller("TestController", TestController); 

    TestController.$inject = []; 

    function TestController() { 
     var vm = this; 

     function testDivClicked(msg) { 
      console.log("message:", msg); 
     } 
    } 
})(); 

當我clic k在最裏面div,我想testDivClicked()記錄我點擊它。

我在這個設置中錯過了什麼,這將使我得到ng-click工作?

+0

試試這個'vm.testDivClicked =函數(MSG){執行console.log( 「信息:」 MSG):}' –

+0

能否請您提供一個plunker。 –

+0

爲什麼不使用角度$範圍服務?我可以知道你的angularjs版本嗎? –

回答

1

您應該寫vm.testDivClicked = function(msg)而不是function testDivClicked。你聲明瞭一個本地函數。

0

提供用於創建控制器的模塊名稱myApp.test是錯誤的。而是使用angular.module("myApp")

所以,你的測試控制器應

(function() { 
    "use strict"; 

    angular 
     .module("myApp") 
     .controller("TestController", TestController); 

    TestController.$inject = []; 

    function TestController() { 
     var vm = this; 

     function testDivClicked(msg) { 
      console.log("message:", msg); 
     } 
    } 
})(); 
0

正如前面由亞歷山大說,功能testDivClicked功能不與vm(this)有關。所以它在dom中不被識別爲vm.testDivClicked('test-container')

這裏是修改部分。

function TestController() { 
     var vm = this; 

     vm.testDivClicked = function(msg) { 
      console.log("message:", msg); 
     } 
    }