KnockoutJS和AngularJS之间传递变量 [英] Passing variables between KnockoutJS and AngularJS

查看:161
本文介绍了KnockoutJS和AngularJS之间传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  1. 我在我的SPA仪表板创建使​​用淘汰赛。它的工作好。不过,我们需要在我们的仪表盘添加越来越多的复杂的事情,所以我们计划开发仪表板的角剩余部分。


  2. 我的问题是如何传递变量从淘汰赛到角。我尝试使用set和get方法,但它并没有帮助我..
    3.So,我试过这样的,我想在劫函数来设置属性值的时候,这样的..


<李ID =setMgmtEnv>
  &所述; A HREF =JavaScript的:;'数据绑定=点击:setMgmtEnv>
    <跨度>管理机构]< / SPAN>
  &所述; / A>
< /李>

///////主JS文件
变种X =的document.getElementById(setMgmtEnv);
        x.setAttribute(价值,0);
    //////在KO模型
    self.setMgmtEnv =功能(){
                x.setAttribute(价值,1);
            }
    /////////在角我注意到这样的变化变量
   $范围。$腕表(功能(负载){
    返回$ scope.toLoad =的document.getElementById('setMgmtEnv')值。
},功能(为newValue,属性oldValue){
    的console.log($ scope.toLoad2:+ $ scope.toLoad);
    如果($ scope.toLoad){
        的console.log($ scope.toLoad3:+ $ scope.toLoad);
        $ HTTP({
            方法:GET,
            URL:
        })。成功(功能(数据){
            的console.log(数据);
        })错误(功能(数据){
            警报(失败的消息:+ JSON.stringify({
                数据:数据
            }));
        });
    }}


解决方案

在一个应用程序中混合KnockoutJS和AngularJS是一个很大的红旗。要确保你知道你在做什么,或者你可能会更好的角度重写KO部分。

说到这里,我可以尝试回答你问的问题,虽然不是在code的范围内片段您所提供(这是的非常的不清楚)。

有三种主要途径KO可以用角互动(这是你的方向似乎是问):


  1. 它们各自控制自己的一片DOM的。 KO将通知通过JavaScript code角。这将是preferred情况。

  2. 它们各自控制自己的一片DOM的。 KO将通知角通过影响了一块DOM由角实际控制。

  3. 它们共享同一块DOM的控制。 KO通知自动角,因为它会更新DOM当一个变量的变化,和角度的双向绑定挑这件事。

选项2和3是一个灾难。他们的可以的工作要做,但说不好我会离开创建的PoC作为为读者提供一个锻炼; Tibial。

这使得选项1,这在特定的情况下,实际上是有用的。要做到这一点你需要这些成分:


  • 在角的范围以KO视图模型的参考;

  • 在KO的视图模型的相关部分订阅;

  • $范围的呼叫。$适用没有通知角的KO订阅回调改变了范围。

下面是一个〔实施例:

\r
\r

VAR视图模型=功能(){\r
  this.name = ko.observable();\r
};\r
\r
VAR VM =新视图模型();\r
\r
angular.module(demoApp,[])\r
  .controller(myCtrl,[$范围功能($范围){\r
    $ scope.name = vm.name();\r
  \r
    vm.name.subscribe(功能(的newval){\r
      $范围。$应用(函数(){\r
        $ scope.name =的newval;\r
      });\r
    });\r
  }]);\r
\r
ko.applyBindings(VM,的document.getElementById(knockoutArea));

\r

DIV {保证金:5像素;填充:5像素;边框:1px的固体#edd;背景色:#fee; }

\r

&LT;脚本SRC =htt​​ps://ajax.googleapis.com/ajax /libs/angularjs/1.2.23/angular.js\"></script>\r
&所述; SCRIPT SRC =htt​​ps://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js&GT;&下; /脚本&GT;\r
\r
&LT; D​​IV ID =knockoutArea&GT;\r
  &LT;强&GT;敲除LT; / STRONG&GT;&LT; BR&GT;\r
  输入您的姓名:其中,输入数据绑定=为textInput:名称&GT;\r
&LT; / DIV&GT;\r
\r
&LT; D​​IV ID =angularAreaNG-应用=demoAppNG控制器=myCtrl&GT;\r
  &LT;强&GT;&角LT; / STRONG&GT;&LT; BR&GT;\r
  我们知道你的名字是:其中;强&GT; {{名}}&LT; / STRONG&GT;\r
&LT; / DIV&GT;

\r

\r
\r

作为替代方案,因为角似乎是向前发展的方式,你可能要反转的依赖。给KO到角的引用,使对角范围的code调用更新的遗产的一部分。这使得您的KO code脏了很多,但保持你的未来codeBase的清洁剂。

  1. I am using Knockout in my SPA dashboard creation. Its working good.But we need to add more and more complex things in our dashboard, so we planned to develop the remaining part of dashboard in Angular.

  2. My question is how can i pass variables from knockout to Angular. I tried using set and get methods, but it didn't helped me.. 3.So, i tried like this, i would like to set an attribute value in the ko function when, like this..

<li id="setMgmtEnv">
  <a href='javascript:;' data-bind="click: setMgmtEnv">
    <span>Manage Orgs</span>
  </a>
</li>

///////in Main JS file
var x = document.getElementById("setMgmtEnv"); 
        x.setAttribute("value", "0");
    ////// In KO model
    self.setMgmtEnv =  function(){
                x.setAttribute("value", "1");           
            }
    ///////// In Angular i am noticing the change variable like this
   $scope.$watch(function(load) {
    return $scope.toLoad = document.getElementById('setMgmtEnv').value;
}, function(newValue, oldValue) {
    console.log("$scope.toLoad2 : " + $scope.toLoad);
    if ($scope.toLoad) {
        console.log("$scope.toLoad3 : " + $scope.toLoad);
        $http({
            method : 'GET',
            url : url
        }).success(function(data) {
            console.log(data);
        }).error(function(data) {
            alert("Failure message: " + JSON.stringify({
                data : data
            }));
        });
    }}

解决方案

Mixing KnockoutJS and AngularJS in one application is a big red flag. Be sure you understand what you're doing, or you'll probably be better off rewriting the KO parts in Angular.

Having said that, I can try to answer the question you're asking, though not in the context of the code snippet you provided (which is very unclear).

There are three main ways KO can interact with Angular (which is the direction you seem to be asking about):

  1. They each control their own piece of the DOM. KO will "notify" Angular through Javascript code. This would be the preferred situation.
  2. They each control their own piece of the DOM. KO will "notify" Angular by influencing a piece of the DOM actually controlled by Angular.
  3. They have shared control of the same piece of the DOM. KO "notifies" Angular automatically because it will update the DOM when a variable changes, and Angular's two-way bindings pick this up.

Option 2 and 3 are a recipe for disaster. They can be done, but are that bad I'll leave creating a PoC as an excercise for the reader.

That leaves option 1, which in specific cases can actually be useful. To do so you need these ingredients:

  • Within Angular's scope a reference to the KO ViewModel;
  • A subscription on the relevant part of KO's ViewModel;
  • A call to $scope.$apply no notify Angular the KO subscription callback has changed the scope.

Here's an exmaple:

var ViewModel = function() {
  this.name = ko.observable("");
};

var vm = new ViewModel();

angular.module("demoApp", [])
  .controller("myCtrl", ["$scope", function($scope) {
    $scope.name = vm.name();
  
    vm.name.subscribe(function(newVal) {
      $scope.$apply(function() {
        $scope.name = newVal;
      });
    });
  }]);

ko.applyBindings(vm, document.getElementById("knockoutArea"));

div { margin: 5px; padding: 5px; border: 1px solid #edd; background-color: #fee; }

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div id="knockoutArea">
  <strong>Knockout</strong><br>
  Type your name: <input data-bind="textInput: name">
</div>

<div id="angularArea" ng-app="demoApp" ng-controller="myCtrl">
  <strong>Angular</strong><br>
  We know your name is: <strong>{{ name }}</strong>
</div>

As an alternative, given that Angular seems to be your way forward, you may want to invert the dependency. Give KO a reference to Angular and make that "legacy" part of your code call updates on the Angular scopes. This makes your KO code a lot dirtier, but keeps your future codebase cleaner.

这篇关于KnockoutJS和AngularJS之间传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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