2014-10-07 27 views
0

我已经在外壳页面(index.html)中初始化了一个属性,我想在通过route.my代码调用的控制器中获取该值。如何获得在外壳页面初始化为控制器的属性值

的index.html:

<html> 
    //loaded all libraries,modules 
    <ng-init="status=false"></ng-init> 
    <ng-init="activator=[{'orders':'active'},{'customers':''},{'about':''}]"></ng-init> 
    <ul class="nav nav-tabs nav-justified" role="tablist" ng-show="status"> 
    <li class="activator.orders"><a href="#customers">Customers</a></li> 
    <li class="activator.customers"><a href="#orders">Orders</a></li> 
    <li class="activator.about"><a href="#about">About</a></li> 
    </ul> 

<ng-view></ng-view> 

</html> 

orderscontroller.js

app.controller('ordersctrl',function($scope,$rootScope,$http,$cookies,$cookieStore,$location) 
{ 
$rootScope.status="true"; 
$rootScope.myname=$cookieStore.get('name'); 
alert($rootScope.activator); //it prints "undefined" 
}); 

customermanager.js

var app=angular.module('customermanager',['ngRoute','ngCookies','ngAnimate','ui.bootstrap']); 

app.config(function($routeProvider) 
      { 

    $routeProvider.when('/', 
         { 

    controller:'loginctrl', 
    templateUrl:'views/loginview.html' 

    }) 
    .when('/orders', 
         { 

    controller:'ordersctrl', 
    templateUrl:'views/ordersview.html' 

    }) 
    .when('/customers', 
         { 

    controller:'customersctrl', 
    templateUrl:'views/customersview.html' 

    }) 
    .when('/about', 
         { 

    controller:'aboutctrl', 
    templateUrl:'views/aboutview.html' 

    }) 
    .otherwise(
     { 
     redirectTo:'/' 

     }); 

}); 

当我点击“#orders”,orderscontroller.js及其相关的看法是called.My要求是通过“激活”属性orderscontroller.js,请帮助。 ..

回答

0

首先,ngInit指令有一个属性:restrict: 'AC'这意味着创建<ng-init/>元素将无法正常工作。

什么是ngInit“允许您评估当前范围中的表达式”(请参阅​​https://docs.angularjs.org/api/ng/directive/ngInit)。所以,如果你想初始化HTML中的值,你应该在控制器的“范围”内执行它,那就是你应该在其中使用ngController指令和相应的ngInit指令。

<div ng-controller="ordersctrl"> 
    <span ng-init="..." /> 
    ... 
</div> 

<div ng-controller="ordersctrl" ng-init="...">...</div> 

我想,你应该也能这里面ng-app(尝试将其添加到您<html>标签)。

但它至少还不够优雅。为什么你想在HTML中初始化你的变量?当您定义它们时,您可以将这些值分配给您的控制器,就像您使用$rootScope.status时所做的那样。

+0

我使用“角路由”来映射视图和控制器...和我需要得到的属性“激活”是在外壳页面(index.html),我想要在任何控制器中访问该属性我我已经更新了我的代码。希望很明显。 – 2014-10-07 12:32:25

+0

尝试将'ng-init'更改为某个节点的属性。 – 2014-10-07 12:41:35

相关问题