NG-模型饼干 [英] Ng-model with Cookie

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

问题描述

我试图从angular.js主页采取的第一个例子,在cookie支持加入。

I'm trying to take the first example from the angular.js homepage and adding in cookie support.

这是我到目前为止有: https://jsfiddle.net/y7dxa6n8/8/

This is what I have so far: https://jsfiddle.net/y7dxa6n8/8/

有:

<div ng-app="myApp">
  <div ng-controller="MyController as mc">
    <label>Name:</label>
    <input type="text" ng-model="mc.user" placeholder="Enter a name here">
    <hr>
    <h1>Hello {{mc.user}}!</h1>
  </div>
</div>

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

myApp.controller('MyController', [function($cookies) {

           this.getCookieValue = function () {
                   $cookies.put('user', this.user);
                   return $cookies.get('user');
            }

           this.user = this.getCookieValue();
}]);

但它不工作,我一直在努力学习的角度。
谢谢

But it's not working, ive been trying to learn angular. Thanks

推荐答案

OK,你检查code再次,这里是你的答案
https://jsfiddle.net/wz3kgak3/

ok, examined your code once again, and here is your answer https://jsfiddle.net/wz3kgak3/


  1. 问题 - 错误的语法:控制器的通知定义,而不是使用[]作为第二个参数
    如果您使用的控制器[],则必须使用这种方式:

  1. problem - wrong syntax: notice definition of controller, not using [] as second parameter If you are using [] in controller, you must use it this way:

myApp.controller('myController的',['$饼干',函数($饼干){
....
}]);

myApp.controller('MyController', ['$cookies', function($cookies) { .... }]);

这长格式为JavaScript uglyfier安全,当参数 $饼干将成为 A b 左右,并且将无法访问为 $饼干,所以你是在告诉控制器:第一个参数在我的功能饼干

this "long" format is javascript uglyfier safe, when param $cookies will become a or b or so, and will be inaccessible as $cookies, so you are telling that controller: "first parameter in my function is cookies

问题:您正在使用的角度1.3.x中,有没有方法PUT和GET在$饼干,这方法只在角1.4+ avalaible,所以你需要使用旧的方式: $ cookies.user ='东西'; 和getter: VAR东西= $ cookies.user;

  1. problem: you are using angular 1.3.x, there is no method PUT or GET in $cookies, that methods are avalaible only in angular 1.4+, so you need to use it old way: $cookies.user = 'something'; and getter: var something = $cookies.user;

的问题 - 你是不是存储的cookie值,模型更新,但cookie不会自动绑定,所以使用$留意收看的变化用户和存放:

problem - you are not storing that cookie value, model is updated, but cookie is not automatically binded, so use $watch for watching changes in user and store it:

$表(用户,功能(newValue)以{
    $ cookies.user = newValues​​;
});

或通过某些事件做(点击提交,或我不知道在哪里)

or do it via some event (click, submit or i dont know where)

编辑:以$范围完整的工作示例
https://jsfiddle.net/mwcxv820/

full working example with $scope https://jsfiddle.net/mwcxv820/

这篇关于NG-模型饼干的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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