在不使用angular.element(Angularjs)

时间:2016-02-12 06:01:02

标签: javascript angularjs

我有以下div

<div ng-controller="MyController as MC" id="div1">                                                                                                                   
    <a href="#" id="1" ng-init="MC.EntityId = 1 , MC.EntityType = 57" ng-click="MC.LoadFiles(MC.EntityId, MC.EntityType)" title="Upload">Upload </a>                                                                                                         
</div>

我想在这里显示我在div1中设置的EntityId和EntityType

<div ng-controller="MyController as MC" id="div2">                                                                                                                   
     EntityId = {{MC.EntityId}}, EntityType = {{MC.EntityType}}                                                                                                      
</div>

如何在不使用angular.element的情况下在LoadFiles函数中为div2设置EntityId和EntityType。

app.controller('MyController', function () {
  this.EntityId = 0;
  this.EntityType = 0;

  this.LoadFiles = function (id, type){
       this.EntityId = id;
       this.EntityType  = type;
  }
});

2 个答案:

答案 0 :(得分:3)

您应该创建一个服务,然后将其注入您的两个控制器,然后保存并检索该服务中的Entities

答案 1 :(得分:1)

您需要使用对象才能执行two-way data binding。 双向数据绑定不适用于primitive type

进行以下更改。

app.controller('MyController', function () {

  this.Entity = {EntityId:0,EntityType:0};

  this.LoadFiles = function (objEntity){
       this.Entity.EntityId = objEntity.EntityId;
       this.Entity.EntityType  = objEntity.EntityType;
  }
});

HTML:

<div ng-controller="MyController as MC" id="div1">
    <a href="#" id="1" ng-init="MC.Entity.EntityId = 1 , MC.Entity.EntityType = 57" ng-click="MC.LoadFiles(MC.Entity)" title="Upload">Upload </a>    
</div>

HTML Div2

<div ng-controller="MyController as MC" id="div2">                                                                                                                   
     EntityId = {{MC.Entity.EntityId}}, EntityType = {{MC.Entity. ntityType}}                                                                                                      
</div>

编辑:

<div ng-controller="MyController as MC" id="div1">
    <a href="#" id="1"  ng-click="MC.LoadFiles(MC.Entity)" title="Upload">Upload </a>    
</div>

<div ng-controller="MyController as MC" id="div2">                                                                                                                   
     EntityId = {{MC.Entity.EntityId}}, EntityType = {{MC.Entity. EntityType}}                                                                                                      
</div>

控制器:

controller('MyController', function () {

  this.Entity = {EntityId:1,EntityType:57};

  this.LoadFiles = function (objEntity){
       this.Entity.EntityId = objEntity.EntityId;
       this.Entity.EntityType  = objEntity.EntityType;
  }
})

Plunker检查