javascript - AngularJS:如何公开服务 API/变量

标签 javascript angularjs angularjs-scope

尝试使用 AngularJS 服务制作一个简单的示例。

我想在我的数据模型(服务)中包含一些变量和函数,并通过 Controller 公开它们并将它们绑定(bind)到 View 。

问题是 Controller / View 以某种方式获取模型的新实例,我真的看不出这有什么用,因为我想使用其他 Controller / View 来查看相同的数据/API服务,而不是每次都创建一个新实例。

这是一个关于 plunker 的示例:http://plnkr.co/edit/AKZLaT2HrkBPMkICsski?p=preview

/*****script.js******/
var app = angular.module('app',  []);

app.service('myService', function() {

  // my data here
  var text = 'text',
      text2 = 'text2';

  // my function here
  var copyText = function(){
      console.log('BEFORE text: '+ text + ' text2: ' + text2);
      text2 = text;
      console.log('AFTER text: '+ text + ' text2: ' + text2);
  };

  // expose my variables/API here
  return {
      text: text,
      text2: text2,
      copyText: copyText
  };
});

app.controller('myCtrl', [ '$scope', 'myService', function($scope, myService){

  $scope.myService = myService;

}]);


/*****index.html******/
...
  <div ng-controller="myCtrl">
    <h1>angular service exposure</h1>
    <input type="text" ng-model="myService.text">
    <p>text: {{ myService.text }}</p> 
    <button ng-click="myService.copyText()">copy text to text2</button>
    <p>text2: {{ myService.text2 }}</p> 
  </div>

如果您打开控制台,当您按下按钮时,您将看到模型的“真实”值,在将文本复制到 text2 之前和之后。哪些不是我在 Controller View 中看到的......

最佳答案

查看我的edit

我做了一些更改,将 ng-model 作为 copyText() 的参数:

 <div ng-controller="myCtrl">
    <h1>angular service exposure</h1>
    <input type="text" ng-model="myService.value">
    <p>text: {{ myService.text }}</p> 
    <button ng-click="myService.copyText(myService.value)">copy text to text2</button>
    <p>text2: {{ myService.value }}</p> 
  </div>

JS

var app = angular.module('app',  []);

app.service('myService', function() {

// my data here
var text = 'text',
    text2 = 'text2';



// my function here
var copyText = function(value){

  console.log('BEFORE text: '+ text + ' text2: ' + text2);
  text2 = value;
  console.log('AFTER text: '+ text + ' text2: ' + text2);
};

// expose my variables/API here
return {
    text: text,
    text2: text2,
    copyText: copyText
  };
});



app.controller('myCtrl', [ '$scope', 'myService', function($scope, myService){

  $scope.myService = myService;

}]);

希望对你有帮助

关于javascript - AngularJS:如何公开服务 API/变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18673290/

相关文章:

javascript - 我如何使用angularjs从异步调用中定义全局变量?

javascript - $location.search() 与外部函数一起使用重置整个 $scope。如何避免呢?

javascript - Angular : Order of custom event handlers & default handler

javascript - 指令中选择输入的两种方式绑定(bind)不起作用

javascript - 在 for 循环中单击 div 获取单个事件

javascript - AngularJS 中的动态 orderBy

javascript - 有人用过 Django 和 JQuery Autocomplete 吗?

javascript - Windows 8 拆分应用程序自定义

javascript - 仅当到达 if 语句时才显示 Tooltip

javascript - 简单的 AngularJS 路由不起作用