重用NG-控制器单 [英] Reused ng-controller as singleton

查看:219
本文介绍了重用NG-控制器单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,NG-控制器控制器创建一个新的实例。我怎么能重复使用在不同的地方我的模板的控制器,并保持相同的模型。

I understand that ng-controller create a new instance of controller. How could I reused the controller in different place of my template and keep the same model.

我尝试自己找出,但我在AngularJs是新的,有点失落...

I try to find out by myself but I am new in AngularJs and a bit lost...

请参阅我的Plunker例如: http://plnkr.co/edit/VGLEcdlY4IaAJmJPWhQ7 p = preVIEW

See my example in Plunker: http://plnkr.co/edit/VGLEcdlY4IaAJmJPWhQ7?p=preview

HTML

<body ng-app="app">
    <div ng-controller="test">
        <label ng-click="test()">Test: {{ name }}</label><br/>
        <input type="text" ng-model="name" />
    </div>
    <p>Here some other ng-controller...</p>
    <div ng-controller="test">
        <label ng-click="test()">Test: {{ name }}</label><br/>
        <input type="text" ng-model="name" />
    </div>
</body>

的js

angular
.module('app', [])
.controller('test', function($scope) {
    $scope.name = 'hello world';
    $scope.test = function(){ alert('alert'); };
})

的2字段不连接到相同的模型/范围,如何使该单并有两个输入相同的模型。

The 2 fields are not connected to the same model/scope, how can make this singleton and have the same model for both input.

推荐答案

我也有类似的情况太多了,我觉得你唯一可以做的就是使用的服务。

I had similar case too, and I think the only thing you can do is using service.

angular
.module('app', [])
.controller('test', function($scope, singleton) {
    $scope.name = singleton.getField();


}).service('singleton', function(){
  var field = {value : 'hello world'};


  var getField = function(){
    return field;
  }

  return {
    getField : getField
  };

});

下面我用'场'作为一个对象,因为在这种情况下,你必须在两个控制器链接到同一个对象。

Here I used 'field' as an object because in this case you'll have link to the same object in both controllers.

http://plnkr.co/edit/8yXY2qsIqcBtTqZDUxSa?p=$p$ PVIEW

这篇关于重用NG-控制器单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆