Angular JS:占位符没有得到解决

时间:2017-07-11 10:19:57

标签: javascript angularjs

我的角度js代码没有解析占位符,而我试图在运行时解析它。

Js代码:

var message ={s:"hello {{name}}"};

angular.module("myapp",[]).controller("myctrl", function($scope){

  var ctrl=this;

  $scope.name="david";
  $scope.w=message.s;

  $scope.call=function(){
    //alert(message);
  };

});

HTML:

<div ng-app="myapp">
    <div ng-controller="myctrl as ctrl">
        {{w}}
        <input type="text" ng-model="ctrl.name" />
        <input type="submit" ng-click="call();" />
    </div>
</div>

预期输出为:hello david;

附加小提琴链接:https://jsfiddle.net/rakotkar/o46coezd/2/

2 个答案:

答案 0 :(得分:0)

您将控制器混合为语法和$scope。当您使用控制器作为语法时,您必须使用this关键字而不是$scope

<强> JS

var message ={s:"hello "};

angular.module("myapp",[]).controller("myctrl",function(){

  var ctrl = this;

  ctrl.name ="david";
  ctrl.w = message.s;
  ctrl.call = function(){
    //alert(message);
  };

});

<强> HTML

<div ng-app="myapp">
    <div ng-controller="myctrl as ctrl">
        {{ctrl.w}}{{ctrl.name}}
        <input type="text" ng-model="ctrl.name" />
        <input type="submit" ng-click="call();" />
    </div>
</div>

<强>演示https://jsfiddle.net/o46coezd/4/

有关控制器的更多信息,请参阅语法:AngularJs "controller as" syntax - clarification?

答案 1 :(得分:0)

你可以尝试如下。当你试图从外部模块访问范围时,我认为这是不可能的。

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<body>

<div ng-app="myapp">
<div ng-controller="myctrl as ctrl">
{{w}}
<input type="text" ng-model="ctrl.name"/>
<input type="submit" ng-click="call();"/>
</div>
</div>
<script>
var message ={s:"hello"};
angular.module("myapp",[]).controller("myctrl", function($scope){

  var ctrl=this;
  $scope.text = message;
  $scope.name="david";
  $scope.w= $scope.text.s + ' ' + $scope.name;

  $scope.call=function(){
    //alert(message);
  };

});
</script>

</body>
</html>