这是指Angularjs

时间:2017-03-01 21:23:35

标签: angularjs

基本上,按钮点击将从ShowHide()调用MyController功能,如果$scope.IsVisible==false,则复制该值。

但是在这里,这个词指向$scope的{​​{1}}。 而console.log的输出证明了这一点,虽然这是我期待的事情,但有人能解释我这是怎么发生的?这是因为Javascript原型吗?

formController

脚本:

<div ng-app="MyApp" ng-controller="MyController">
    <div ng-controller="formController">
        <div ng-bind="broker.info"></div>
        <div ng-show="IsVisible">Some content to be hide</div>
        <button ng-click="ShowHide()">ok</button>
    </div>
</div>

截图:

1

1 个答案:

答案 0 :(得分:0)

您的问题的简短回答是使用controllerAs语法。

<!DOCTYPE html>
<html>
<head>
    <title>ControllerAs</title>
    <style>
        div{
            border: 1px solid black;
            margin: 10px;
            padding: 10px;
        }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.14/angular.min.js"></script>

    <script type="text/javascript">
        var app = angular.module('app', []);
        app.controller('test0', function($scope){
            $scope.message = "Test0";
        });
        app.controller('test1', function($scope){
            $scope.message = "Test1";
        });
        app.controller('test2', function(){
            this.message = "Test2";
        });
        app.controller('test3', function($scope){
            this.message = "Test3";
            var ctrl = this;
            this.changeMessage = function(){
//              ctrl.message = this.newMessage;// doesn't work
                ctrl.message = new String($scope.newMessage);
            }
            $scope.$watch(angular.bind(this, function(){
                return this.message;
            }), function (newVal, oldVal) {
                if(newVal.toString() === oldVal.toString()){
                    console.log("No change");
                } else {
                    console.log("message changed");
                }
              });
        });
    </script>

</head>
<body ng-app="app">

<div ng-controller="test0">
    <h2>message: {{message}}</h2>
    <div ng-controller="test1">
        <h2>message: {{message}} </h2>
        <h2>what is parent message: {{$parent.message}}</h2>
        <div ng-controller="test2 as t2">
            <h2>t2.message: {{t2.message}}</h2>
            <div ng-controller="test3 as t3">
                <h2>t3.message: {{t3.message}} </h2>
                <h2>What was first message: {{$parent.$parent.$parent.message}} </h2>
                <h2>Get previous message: {{t2.message}}</h2>
                <hr/>
                <input type="text" placeholder="Enter new message" ng-model="newMessage"><button ng-click="t3.changeMessage()">Change This Message</button>
            </div>
        </div>
    </div>
</div>
</body>
</html>