通过ng-click访问AngularJS表达式

20 浏览
0 Comments

通过ng-click访问AngularJS表达式

点击事件后,我无法访问angularjs表达式。\nindex.html\n

    
        {{item.compname}}
    

\n上述代码会填充一个公司名称列表。当我点击某个公司时,会打开company.html。\ncompany.html\n

   
      
   
   
      {{item.compemail}}
      {{item.compbuilding}}
      {{item.compphone}}
   

\n控制器(app.js)\n

$scope.onSelect = function($event, data) {
   console.log(data);
}

\n文件结构\n

root
    +--public
        +--templates
            +--company.html
            +--index.html
        +--javascript
            +--app.js
    +--views
        +main.html

\n我使用ngRoute将index.html和company.html注入到main.html中。\n

app.config(function($routeProvider){
    $routeProvider
    .when ('/', {
         templateUrl: 'templates/home.html',
         controller: 'AppCtrl'
    })
    .when ('/company', {
         templateUrl: 'templates/company.html',
         controller: 'AppCtrl'
    })
});

\n所以当我使用console.log()输出控制器时,它显示了数据数组,但没有将其添加到company.html文档中。我漏掉了什么?

0
0 Comments

问题原因:$scope的作用域问题,无法从$scope的根目录访问item in data中的item

解决方法:

1. 在HTML中使用嵌套的元素结构,将item放在一个父级元素中,然后在$scope.onSelect函数中使用$scope.selected来访问item

2. 确保控制器与模板正确绑定,可以使用ng-controller指令或路由设置来链接视图和控制器。

3. 使用$rootScope来存储选定的项目,但不建议频繁使用$rootScope

4. 当点击链接时,传递项目的标识符作为参数,然后使用$routeParams获取标识符,并在数据数组中查找匹配的项目。

5. 在控制器中注入$rootScope

以上是关于问题原因和解决方法的总结。

0