AngularJS ng控制器指令不接受javascript中的变量(作用域函数),也不给出任何错误

AngularJS ng-controller directive does not accept variable (scope function) from javascript, does not give any error either

本文关键字:函数 错误 任何 作用域 指令 控制器 ng 不接受 javascript 变量 AngularJS      更新时间:2023-09-26

我对angularJS相对陌生,我正在尝试设置一个页面,根据之前的选择调用inturn多个页面。所有的页面都有自己的控制器,所以我试图通过javascript设置控制器和视图src,并在HTML标记中使用它们。

以下是我正在做的事情:
HTML页面:

<div ng-if="sidebarName=='sidebar-device-wire'">
        <div ng-controller="getSidebarCtlr">    
            <div ng-include src="sidebarSrc"></div>
        </div>
    </div>

javascript:

$scope.sidebarSrc="views/sidebars/sidebar-device.html";
$scope.sidebarCtlr="SidebarDeviceCtrl";
$scope.getSidebarCtlr = function(){return $scope.sidebarCtlr;}

但由于某种原因,这并不奏效。我可以得到HTML页面,但控制器没有被调用。有人能告诉我我做错了什么吗?

我还建议使用ngRouteui.router,因为有许多功能不容易从头开始实现(如命名视图、嵌套视图/嵌套状态或解析),而且这些模块经过了很好的测试。

不确定为什么你的控制器没有运行,但我猜在你的设置名称的控制器运行之前,已经对控制器的表达式进行了评估。所以它在编译时总是未定义的。

但是,如果你真的想实现一个非常基本的路由器,你可以在下面的演示中(或在这个小提琴中)这样做。

2015年12月21日更新

以下是我为其他SO问题写的一些路由器示例:

  • 简单的ui.外部示例-jsfiddle
  • 更复杂的嵌套状态示例ui.router-jsfiddle
  • 使用ngRoute-jswiddle的动态链接列表

还请查看ui.router github页面以了解更多信息。

angular.module('simpleRouter', [])
  .directive('simpleView', simpleViewDirective)
  .provider('simpleRoutes', SimpleRoutesProvider)
  .controller('MainController', MainController)
  .controller('HomeController', HomeController)
  .config(function(simpleRoutesProvider) {
    simpleRoutesProvider.state([{
      url: '/',
      templateUrl: 'home.html',
      controller: 'HomeController'
    }, {
      url: '/view1',
      templateUrl: 'view1.html'
    }, {
      url: '/view2',
      templateUrl: 'view2.html',
      controller: function($scope) {
      	$scope.test = 'hello from controller'
      }
    }]);
    simpleRoutesProvider.otherwise('/');
  })
function HomeController($scope) {
	$scope.hello = 'hello from home controller!!';
	console.log('home controller started')
}
function MainController($scope) {
   $scope.hello = 'Main controller test';
}
function simpleViewDirective() {
  return {
    restrict: 'EA',
    scope: {},
    template: '<div ng-include="templateUrl"></div>',
    controller: function($scope, $location, $controller, simpleRoutes) {
    	var childControllerInst;
      $scope.templateUrl = simpleRoutes.currentRoute.templateUrl || simpleRoutes.otherwise.templateUrl;
      
      $scope.$watch(function() {
        return $location.path();
      }, function(newUrl) {
        //console.log(newUrl)
        $scope.templateUrl = simpleRoutes.changeRoute(newUrl);
        
        childControllerInst = $controller(simpleRoutes.currentRoute.controller || function() {}, {$scope: $scope});
        
      });
      
      $scope.$on('$destroy', function() {
      	childControllerInst = undefined;
      })
    },
    link: function(scope, element, attrs) {
    }
  }
}
function SimpleRoutesProvider() {
  var router = {
    currentRoute: {
      templateUrl: ''
    },
    states: [],
    otherwise: {},
    changeRoute: function(url) {
      var found = false;
      angular.forEach(router.states, function(state) {
        //console.log('state', state);
        if (state.url == url) {
          router.currentRoute = state;
          found = true;
        }
      });
      if (!found) router.currentRoute = router.otherwise;
      //console.log(router.currentRoute);
      return router.currentRoute.templateUrl;
    }
  };
  this.state = function(stateObj) {
    router.states = stateObj;
  };
  this.otherwise = function(route) {
  	angular.forEach(router.states, function(state) {
    	if (route === state.url ) {
    		router.otherwise = state;  	
      }
    });
    
    //console.log(router.otherwise);
  };
  this.$get = function simpleRoutesFactory() {
    return router;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="simpleRouter" ng-controller="MainController">
  <script type="text/ng-template" id="home.html">home route {{hello}}</script>
  <script type="text/ng-template" id="view1.html">view1</script>
  <script type="text/ng-template" id="view2.html">view2 {{test}}</script>
  <div simple-view="">
  </div>
  <a href="#/">home</a>
  <a href="#/view1">view1</a>
  <a href="#/view2">view2</a>
  <br/>
  {{hello}}
</div>

这段代码是什么意思?$scope.getSidebarCtlr = function(){return $scope.sidebarCtlr;}

ng-directive需要一个Controller名称,其参数类型为string,并且您不能传递简单的函数,您需要注册一个有效的控制器,通过controller配方将其关联到一个模块。

https://docs.angularjs.org/guide/controller

angular.module('test', []).controller('TestCtrl', function($scope) {
  $scope.greetings = "Hello World";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app="test">
  <article ng-controller="TestCtrl">{{ greetings }}</article>
</section>