javascript - Angular1.3: Access functions from standard controllers, inside a view which uses controllerAs? -
i have simple controller defined in main app.js file, controls opening/closing of navbar , visible on other views of app:
app.js:
.controller('maincontroller', ['$scope', function($scope){ $scope.menuactive = false; $scope.togglemenu = function(){ $scope.menuactive = !$scope.menuactive; } }]);
index.html:
<nav class="side-menu" ng-class="{ 'side-menu-open' : menuactive }"> <ul> <li>link1</li> <li>link2</li> </ul> </nav> <!--other views::.....--> <div ui-view></div>
all other views(which use controlleras), have button ng-click using access above $scope.togglemenu() function , ng-class, not work, , don't errors either:
view1.html :
<span class="btn btn-default" ng-click="togglemenu()"> menu </span>
view1.js:
angular .module('myapp.view1', []) .controller('view1ctrl', [ function(){ ................ } ]);
also, reason have done way again because navbar persistent throughout app. go against best practices chance?
if using .. controller ..
syntax, make sure using controllers. don't selective it.
next, when using syntax, need not inject $scope
object. need instead use this
variable , attach properties or functions associate $scope
object this
object instead.
thus,
$scope.togglemenu = function(){ $scope.menuactive = !$scope.menuactive; }
becomes
this.togglemenu = function(){ this.menuactive = !this.menuactive; }
finally in view, sure associate each expression controller.
<div ng-controller="maincontroller main"> <nav class="side-menu" ng-class="{ 'side-menu-open' : main.menuactive }"> <ul> <li>link1</li> <li>link2</li> </ul> </nav> <div ui-view> <!-- assuming following gets compiled ui-view --> <span class="btn btn-default" ng-click="main.togglemenu()"> menu </span> </div> </div>
you can further hints on using controller as
syntax here
Comments
Post a Comment